开发者

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.

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.


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.

Let me know if that helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜