将单元格值添加到整数 (Excel-VBA)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16096650/
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
Adding Cell Value to an Integer (Excel-VBA)
提问by sweetname
With years of programming experience (beginner with VBA, however), online references, and search engines I'm yet frustrated to the utmost with my inability to get this to work.
凭借多年的编程经验(不过是 VBA 的初学者)、在线参考资料和搜索引擎,我对无法实现这一点感到非常沮丧。
I've spent at least two hours trying every combination of CInt, .Range, With/End With, .Value, Cells, etc. that I could possibly think of and it just keeps failing on the "sum = sum + ..." line:
我已经花了至少两个小时尝试我可能想到的 CInt、.Range、With/End With、.Value、Cells 等的每种组合,但它只是在“sum = sum + ... “ 线:
Public Sub Fill_InnerData()
Dim GNumber As Range
Set GNumber = Range("GenerateNumber")
Dim Data As Range
Set Data = Range("DATA_INNER")
For r = 1 To Data.Rows.Count
For c = 1 To Data.Columns.Count
If Data.Cells(r, c) = "" Then
If c > r Then
Data.Cells(r, c) = 0
Else
Dim x As Integer
x = r - c + 1
Dim y As Integer
y = 2
Dim sum As Integer
sum = 1
For i = 1 To c
sum = sum + CInt(Worksheets("Data").Range(Cells(x, y)).Value)
y = y + 1
Next
End If
End If
Next
Next
End Sub
By "failing" I mean getting this error:
“失败”是指收到此错误:
Run-time error '1004':
Application-defined or object-defined error
运行时错误“1004”:
应用程序定义或对象定义的错误
I've received that error at the mentioned line with EVERY combination that I tried.
我在提到的行中收到了我尝试过的每个组合的错误。
What am I doing wrong?
我究竟做错了什么?
回答by Kazimierz Jawor
The think here is with your syntax referring to range. It should be enough to cut it a bit and do it this way:
这里的想法是你的语法指的是范围。把它剪短一点并这样做就足够了:
Sum = Sum + CInt(Worksheets("Data").Cells(x, y).Value)
According to my experiences range requires address string inside parenthesis if only one argument is provided. Or you can put Cells if you provide both starting and ending range points. This two simple lines has correct syntax:
根据我的经验,如果只提供一个参数,则范围需要括号内的地址字符串。或者,如果您同时提供起点和终点范围点,则可以放置单元格。这两个简单的行具有正确的语法:
Range(Cells(1,1), Cells(2,2)).Select
Range(Cells(1,1).Address).Select
This is not valid:
这是无效的:
Range(Cells(1,1)).Select 'error 1004 here