VBA中两个阵列的相关性

时间:2017-10-31 04:21:27

标签: arrays excel vba

大家。我是VBA的新手,最近遇到了这个问题,当我在两个范围上运行以下功能时,excel会发出警告 - "运行时错误' 1004':方法'相关及'对象'工作表功能'失败&#34。 我想知道我的情况有什么不对,以及如何绕过这个警告。非常感谢。

'Calculate correlation coefficient with whatever sizes of two data sets
Function CorrelationDifferentSizes(data1, data2) As Double
    Dim length1 As Integer
    Dim length2 As Integer
    'length1 = UBound(data1) - LBound(data1) + 1
    'length2 = UBound(data2) - LBound(data2) + 1
    length1 = data1.Rows.Count
    length2 = data2.Rows.Count


Dim tmp1() As Variant
Dim tmp2() As Variant
ReDim tmp1(1 To length2)
ReDim tmp2(1 To length1)



If length1 > length2 Then
    Dim i As Integer
    Dim j As Integer
    For i = 1 To length2
        tmp2(i) = data2.Cells(i, 1)
    Next i
    For j = 1 To (length1 - length2)
        tmp2(length2 + j) = 0
    Next j

ElseIf length2 > length1 Then
    Dim m As Integer
    Dim n As Integer
    For m = 1 To length1
        tmp1(m) = data1.Cells(m, 1)
    Next m
    For n = 1 To (length2 - length1)
        tmp1(length1 + n) = 0
    Next n
End If

'Dim a1
'Dim a2
'a1 = Array(tmp1)
'a2 = Array(tmp2)

CorrelationDifferentSizes = Application.WorksheetFunction.Correl(tmp1, tmp2)
End Function

1 个答案:

答案 0 :(得分:2)

您需要先确定两个范围之间的最大行数,然后将数组重新调整为最大计数。将数组声明为数字类型将阻止您将值启动为0。

'Calculate correlation coefficient with whatever sizes of two data sets
Function CorrelationDifferentSizes(data1 As Range, data2 As Range) As Double
    Dim arr1() As Double, arr2() As Double, x As Long
    Dim Count As Long
    Count = Application.WorksheetFunction.Max(data1.Rows.Count, data2.Rows.Count)
    ReDim arr1(1 To Count)
    ReDim arr2(1 To Count)

    For x = 1 To data1.Rows.Count
        arr1(x) = data1(x)
    Next

    For x = 1 To data2.Rows.Count
        arr2(x) = data2(x)
    Next

    CorrelationDifferentSizes = Application.WorksheetFunction.Correl(arr1, arr2)
End Function