我有这个代码我写的是为了获得一个没有重复值的总和。我有一个包含1424行和2列(字符串和值)的表。所以我看一下之前的值,如果当前值不相同,我总算一下。
Function sumAll()
Dim firstRow As Long
firstRow = 5
Dim lastRow As Long
lastRow = 12
Dim aRow As Long
Dim sumResult As Long
sumResult = 0
Dim previousValue As Long
previousValue = -1
For aRow = firstRow To lastRow
If Cells(aRow, 2).Value <> previousValue Then
sumResult = sumResult + Cells(aRow, 2)
previousValue = Cells(aRow, 2)
End If
Next aRow
sumAll = sumResult
End Function
但是,如果将lastRow
设为30,则会出现问题 - 我发现#VALUE!
错误。但为什么?可能达到的最大值sumResult
为60 912 997 662
。 Long
应该最多9,223,372,036,854,775,807。
编辑:好的,我在Long
上更改了Double
,但它仍然给我错误:
Function sumAll()
Dim firstRow As Long
firstRow = 5
Dim lastRow As Long
lastRow = 600
Dim aRow As Long
Dim totalDoubles As Long
totalDoubles = 0
Dim sumResult As Double
sumResult = 0
Dim previousValue As Double
previousValue = -1
For aRow = firstRow To lastRow
If Cells(aRow, 2).Value <> previousValue Then
sumResult = sumResult + Cells(aRow, 2)
previousValue = Cells(aRow, 2)
Else
totalDoubles = totalDoubles + 1
End If
Next aRow
sumAll = sumResult
MsgBox ("end: " & totalDoubles)
End Function
答案 0 :(得分:2)
这适用于我使用Double或Variant。 Long Integer的大小只有4个字节。范围是-2,147,483,648到2,147,486,647。 Double是8个字节,Variant是16个字节。这对我很有用:
Function sumAll() As Variant
Dim firstRow As Integer: firstRow = 5
Dim lastRow As Integer: lastRow = 30
Dim aRow As Integer
Dim sumResult As Variant: sumResult = 0
Dim previousValue As Variant: previousValue = -1
For aRow = firstRow To lastRow
If Cells(aRow, 2).Value <> previousValue Then
sumResult = sumResult + Cells(aRow, 2)
previousValue = Cells(aRow, 2)
End If
Next aRow
sumAll = sumResult
End Function
Here您可以看到VBA数据类型&#39;的范围内。