VBA函数在输出范围周围创建一个0层



我已经得到了以下宏和函数工作,但粘贴的结果在左侧和结果的顶部有一层零。希望你们能找出我代码中的错误。我相信错误在函数中:

Sub AutoCovariance()
Dim DataRange As Range
Dim VarCovarOutPutRange As Range
Dim NumberOfReturns As Long
Dim NumberOfStocks As Long
Dim ArrayColumnsCounter As Double
Dim ArrayRowsCounter As Double
Dim ReturnsArray() As Double
Dim DataReturns() As Variant
Dim DataRowCounter As Long
Dim DataColumnCounter As Long
Dim Stock As Long
Dim dAutoCoVar() As Double
Set DataRange = ThisWorkbook.Worksheets(Sheet1.Name).ListObjects("DataTable").DataBodyRange
NumberOfReturns = ThisWorkbook.Worksheets(Sheet1.Name).ListObjects("DataTable").DataBodyRange.Rows.Count
NumberOfStocks = ThisWorkbook.Worksheets(Sheet1.Name).ListObjects("DataTable").Range.Columns.Count
ArrayColumnsCounter = 0
ArrayRowsCounter = 0
ReDim Preserve ReturnsArray(10, 1)
    ' Creating returns array
    For DataColumnCounter = 1 To NumberOfStocks
        ArrayRowsCounter = ArrayRowsCounter + 1
        For DataRowCounter = 1 To NumberOfReturns
            ArrayColumnsCounter = ArrayColumnsCounter + 1
            ReDim Preserve ReturnsArray(NumberOfStocks, ArrayColumnsCounter)
            For Stock = 1 To NumberOfStocks
                ReturnsArray(Stock, ArrayColumnsCounter) = DataRange(DataRowCounter, Stock).Value
            Next Stock
        Next DataRowCounter
        ArrayColumnsCounter = ArrayColumnsCounter - 100
    Next DataColumnCounter
' Transfer ReturnsArray Data to DataReturns
ReDim DataReturns(NumberOfReturns, NumberOfStocks)
DataReturns = Application.WorksheetFunction.Transpose(ReturnsArray)

' calculate the autocovariance matrix
dAutoCoVar = Autocovar(DataReturns)
' write to the worksheet, for debug
Set VarCovarOutPutRange = ThisWorkbook.Worksheets(Sheet1.Name).Range(Cells(1, NumberOfStocks + 2), Cells(NumberOfStocks, NumberOfStocks * 2 + 2))
VarCovarOutPutRange.Value = dAutoCoVar
End Sub

和函数

Function Autocovar(DataReturns() As Variant) As Double()
Dim dArrResult() As Double
Dim j As Long, k As Long
' redim the result array as a square array.
ReDim dArrResult(1 To UBound(DataReturns, 2), 1 To UBound(DataReturns, 2))
' calculate the autocovariance matrix
For j = 1 To UBound(DataReturns, 2)
    For k = 1 To UBound(DataReturns, 2)
        With Application.WorksheetFunction
            dArrResult(j, k) = .Covariance_S(.Index(DataReturns, 0, j), .Index(DataReturns, 0, k))
        End With
    Next k
Next j
Autocovar = dArrResult
End Function

这个问题听起来很典型,因为数组索引错误。

你的数组操作都假设第一个索引是1。但是默认情况下,如果你像这样重新定义一个数组:

ReDim DataReturns(NumberOfReturns, NumberOfStocks)

索引将从0开始

试着在你的模块开头添加这一行:

Option Base 1

将所有未显式声明为Dim ar(x to y)的数组的第一个索引设置为基础索引1。

相关内容

  • 没有找到相关文章

最新更新