我使用VBA已经很长时间了,并且我对它有相当的经验。不过,有时候,他的怪念头还是让我大吃一惊.为了使文件具有一些可访问的功能,我选择了在脚本上进行每一次计算。为此,我使用一些double数据填充数组:
Dim DT01() As Double: ReDim DT01(1 To N03) As Double
Dim R As Long: R = 1: Dim N As Long: Dim P As Double
For x = 1 To N01
    N = SH01.Cells(x + 4, 15).Value: P = SH01.Cells(x + 4, 14).Value
    For y = 1 To N: DT01(R) = P: R = R + 1: Next y
Next xDT01数组很长(N03 = 495258),前面的例程填充数组就像我想的那样。我甚至做了以下几点:
For x = 1 To 495258
    SH01.cells(x, 1).FormulaR1C1 = DT01(x)
Next x来检查我是否在脚本上犯了一个错误来填充数组。这段代码可以用数组的正确值编写工作表SH01的第一列。
如果计算列的和,则得到292547224.4,这是正确的值。但是,如果我在VBA上使用VBA,就会得到1535172.8。当我看到这一点时,我试着计算其他东西,结果总是不同的:
'On Excel:
    =AVERAGE(A1:A495258) = 598,6
'On VBA:
    Application.Average(DT01) = 42.1
'On Excel:
    =MAX(A1:A495258) = 3622.7
'On VBA:
    Application.Max(DT01) = 186.8    
'On Excel:
    =COUNT(A1:A495258) = 495258
'On VBA:
    Application.Count(DT01) = 36506当我看到最后的结果时,我马上就知道我必须问别人这个问题.有人知道这里发生了什么吗?
更新:
我尝试用一个loop计算数组的和,通过它的所有术语:
Dim SIGMA As Double: SIGMA = 0
For x = 1 To UBound(DT01)
    SIGMA = SIGMA + DT01(x)
Next x我得到了正确的结果(292547224.4),所以为什么我仍然用Application.Sum(DT01)获得1535172.8
发布于 2018-11-29 15:47:48
这不是一个理想的答案,所以有人可能会充实到体面的文件。我发现VBA中数组上的和只工作到长度36506 (从1开始)。
但是,您可以将值数组写入范围,然后将该范围引用传递给Application.Sum并获得正确的值。
Option Explicit
Public Sub test()
    Dim rng As Range, c As Range, i As Long
    Set rng = Range("A1:A495258") 'A1 has value 1, A2 has 2 etc.
    Debug.Print "Application.Sum(rng) " & Application.Sum(rng)   '<==  122640490911
    Debug.Print " Application.Sum(Application.Transpose(rng.Value)) " & Application.Sum(Application.Transpose(rng.Value))   '<== 666362271
    Dim arr3()
    ReDim arr3(1 To 495258)
    For Each c In rng
        i = i + 1
        arr3(i) = c.Value
    Next
    Debug.Print " Application.Sum(arr3) with  arr3(1 To 495258) " & Application.Sum(arr3)
    Debug.Print "Application.WorksheetFunction.Sum(arr3) " & Application.WorksheetFunction.Sum(arr3)
End Sub或者编写您自己的自定义一维和函数:
Option Explicit
Public Sub test()
    Dim arr3(), c As Range, rng As Range, i As Long
    Set rng = Range("A1:A495258")
    ReDim arr3(1 To 495258)
    For Each c In rng
        i = i + 1
        arr3(i) = c.Value
    Next
    Debug.Print SumArray(arr3)
End Sub
Public Function SumArray(ByVal arr As Variant) As Variant ' double
    Dim i As Long
    For i = LBound(arr, 1) To UBound(arr, 1)
        SumArray = SumArray + arr(i)
    Next
End Functionhttps://stackoverflow.com/questions/53541475
复制相似问题