如何使用 VBA 增加 Excel 中的单元格值?错误:类型不匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2935693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I Increase cell value in Excel using VBA? Error: Type mismatch
提问by Ivan Prodanov
I'm writing a macro, but because I'm working for first time in vb, I faced problems.
我正在写一个宏,但是因为我是第一次用 vb 工作,所以遇到了问题。
My code:
我的代码:
Cells (1, 1).Select
Dim tempvar As Integer
tempvar = Val(Selection.Value) // error
Selection.Value = tempvar + 1
What my code should be:
我的代码应该是什么:
Cells(1,1).Value+=1
I get error "type mismatch". How do I accomplish that?
我收到错误“类型不匹配”。我如何做到这一点?
EDIT: Row 1, Cell 1 is merged. It consists of 4 columns, so it is Row 1, Cell 1,2,3,4 in one column. If the cell is not merged then there is no problem.
编辑:第 1 行,单元格 1 已合并。它由4列组成,因此一列是第1行,单元格1、2、3、4。如果单元格未合并,则没有问题。
回答by goggin13
How about just this:
怎么样:
Cells(1,1).Value = Cells(1,1).Value + 1
Selecting cells and ranges to work with them in VBA isn't necessary (and is much slower), you can just refer to them directly. I'm actually not positive what above will do if Cells(1,1) has the value "hello" or not a number, but it will work if its valid. You can use IsNumeric() if you want to test the value in the cell to be sure.
没有必要在 VBA 中选择单元格和范围来处理它们(而且速度要慢得多),您可以直接引用它们。如果 Cells(1,1) 的值为“hello”或不是数字,我实际上并不肯定上面会做什么,但如果它有效,它就会起作用。如果您想测试单元格中的值以确保确定,您可以使用 IsNumeric()。
Let me know if that helps!
如果这有帮助,请告诉我!

