我正在研究一种代码,该代码为某些数据生成协方差矩阵,特别是2列(即2x2矩阵)。发生的事情是代码完美无缺,现在它没有任何重大改变(只是用它做了一个函数)。代码运行,显示MsgBox,当它必须计算矩阵时,它只是跳到所有行的末尾。
代码:
Function GetBaseRate(ranges() As Variant, Days() As Variant) As Object
' Get Data from Data Base
' Use this array to render the bucket titles
Dim Covariance As Object
Dim Cov As Variant
Set Covariance = CreateObject("Scripting.Dictionary")
Set sh = ThisWorkbook.Worksheets("AUX")
' Get Covariance for each range
limit = UBound(ranges)
MsgBox limit
For i = 0 To limit
MsgBox ranges(i) & " - " & Days(i)
Next i
For i = 0 To limit
sh.UsedRange.ClearContents
' query for each day
MsgBox ranges(i) & " - " & Days(i)
Query = "SELECT TASA FROM [NVSSQLBI].[MESA].[dbo].[CURVA_BASE_CLP_ON_FECHA] WHERE DIAS ='" & Days(i) & "' AND FECHA > '" & DateAdd("yyyy", -5, Date) & "' ORDER BY FECHA DESC"
Query2 = "SELECT TASA FROM [NVSSQLBI].[MESA].[dbo].[CURVA_BASE_CLF_ON_FECHA] WHERE DIAS ='" & Days(i) & "' AND FECHA > '" & DateAdd("yyyy", -5, Date) & "' ORDER BY FECHA DESC"
aux = BDconexion2(Query)
aux2 = BDconexion2(Query2)
Count = 1
' CLP
For Each element In aux
sh.Cells(Count, 1).Value = element
Count = Count + 1
Next element
Count = 1
' UF
For Each element In aux2
sh.Cells(Count, 2).Value = element
Count = Count + 1
Next element
' Generate Cov
Cov = VarCov(Range("A1:B" & Count - 1))
'Debug.Print Cov(0, 0) & " - "
Covariance.Add CStr(ranges(i)), Cov
Next i
GetBaseRate = Covariance
End Function
它对数据库进行sql查询,并将数据放入工作表中,以便以后计算它的协方差矩阵。 计算矩阵的代码是这样的:
Function VarCov(rng As Range) As Variant
' Returns covariance matrix
Dim i As Integer
Dim j As Integer
Dim colnum As Integer
Dim Matrix() As Double
colnum = rng.columns.Count
ReDim Matrix(colnum, colnum)
For i = 1 To colnum
For j = 1 To colnum
Matrix(i - 1, j - 1) = Application.WorksheetFunction.Covar(rng.columns(i), rng.columns(j))
Next j
Next i
VarCov = Matrix
End Function
我不知道为什么它不起作用,我使用的是以前的版本,它根本没有失败。 调试后,失败点位于
Matrix(i - 1, j - 1) = Application.WorksheetFunction.Covar(rng.columns(i), rng.columns(j))
过去工作完美的行,现在它不会抛出任何错误只是在函数后面的行(一个MsgBox说"完成")
答案 0 :(得分:1)
尝试将工作表对象添加到要传递给VarCov函数的范围。即 - 尝试更改
Cov = VarCov(Range("A1:B" & Count - 1))
到
Cov = VarCov(sh.Range("A1:B" & Count - 1))
假设sh是范围所在的工作表。
答案 1 :(得分:0)
你能写下这个,看看你在即时窗口中得到了什么吗?
debug.print colnum
For i = 1 To colnum
For j = 1 To colnum
Matrix(i - 1, j - 1) = Application.WorksheetFunction.Covar(rng.columns(i), rng.columns(j))
debug.print i
debug.print j
debug.print Matrix(i - 1, j - 1)
debug.print "---------"
Next j
Next i