将数组传递给Excel VBA中的函数时键入不匹配错误

时间:2014-02-22 20:22:02

标签: arrays excel-vba vba excel

我正在尝试在VBA中编写一些能够计算投资组合差异的东西。我陷入了计算投资组合中所有可能对的协方差的中间步骤。

我创建了一个函数,它接受两个包含双精度数组的数组作为输入并计算covariannce。下面的代码包含一个未显示的另一个函数“Mean”的调用。

Public Function CalcCov(A() As Double, B() As Double) As Double

Dim AvgA As Double
Dim AvgB As Double
Dim Cov As Double

AvgA = Mean(A)
AvgB = Mean(B)

Cov = 0
If UBound(A) = UBound(B) Then
    For I = 1 To UBound(A)
        Cov = Cov + ((A(I) - AvgA) * (B(I) - AvgB)) / UBound(A)
    Next I
ElseIf UBound(A) > UBound(B) Then
    For I = 1 To UBound(B)
        Cov = Cov + ((A(I) - AvgA) * (B(I) - AvgB)) / UBound(B)
    Next I
Else
    For I = 1 To UBound(A)
            Cov = Cov + ((A(I) - AvgA) * (B(I) - AvgB)) / UBound(A)
    Next I
End If

CalcCov = Cov

End Function

从下面显示的主子程序调用此函数。下面的代码应该创建一个代表历史市场数据的双精度数组,称为tickerMD。然后,tickerMD的实例应该存储在称为tickersMD的变体数组中。然后循环应该通过tickersMD运行,并且一次将两个数组传递给CalcCov函数。我得到一个类型不匹配错误指向代码的星号部分。我不明白为什么。

Public Sub Covariances()

Dim NumTickers As Double
Dim NumDays As Double
Dim NumCombinations As Double

NumTickers = Sheet4.Cells(1, 2)
NumDays = Sheet3.Cells(1, 2)
NumCombinations = (NumTickers ^ 2) / 2

Dim tickerMD() As Double' Holds the market-data for a single security
Dim tickersMD() As Variant  ' Holds the market-data arrays
Dim CovMarix() As Variant


ReDim tickersMD(NumTickers)
For Tickers = 0 To NumTickers - 1
    ReDim tickerMD(NumDays)
    For Days = 0 To NumDays - 1
         tickerMD(Days) = Sheet3.Cells(3 + Days, Find(Sheet4.Cells(Tickers + 1)))
    Next Days
    tickersMD(Tickers) = tickerMD
Next Tickers

ReDim CovMatrix(NumCombinations)
For I = 0 To NumTickers - 1
    For J = I + 1 To NumTickers - 1
        **CovMatrix(I) = CalcCov(tickersMD(I), tickersMD(J))**
    Next J
Next I


End Sub

0 个答案:

没有答案