VBA中两个数组的相关性

大家。 我是VBA的新手,最近碰到这个问题,当我在两个范围运行以下函数时,excel给出了一个警告 – “运行时错误'1004':对象'WorksheetFunction'的方法'Correl'失败。 “ 我想知道我的情况有什么问题,我怎样才能解决这个警告。 非常感谢。

'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 

您需要先确定两个范围之间的最大行数,然后将数组重新设置为最大值。 将数组声明为数字types将防止您必须将值初始化为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