简体   繁体   English

如何使用VBA在Excel中增加单元格值? 错误:类型不匹配

[英]How do I Increase cell value in Excel using VBA? Error: Type mismatch

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. 编辑 :行1,单元格1被合并。 It consists of 4 columns, so it is Row 1, Cell 1,2,3,4 in one column. 它由4列组成,所以它是第一行的第1行,单元1,2,3,4。 If the cell is not merged then there is no problem. 如果该单元格未合并,则没有问题。

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. 不需要选择单元格和范围以在VBA中使用它们(并且速度要慢得多),您可以直接引用它们。 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. 我实际上并不肯定,如果Cells(1,1)的值是“ hello”或没有数字,那么上面的方法会起作用,但是如果有效,它将起作用。 You can use IsNumeric() if you want to test the value in the cell to be sure. 如果要测试单元格中的值以确保确定,可以使用IsNumeric()。

Let me know if that helps! 让我知道是否有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM