VBA,编译错误,预期数组

时间:2018-06-15 21:03:27

标签: excel excel-vba vba

我正在尝试运行我的代码,遇到编译错误。 目前我正在努力优化我的代码,因为我读到我需要更多地使用Variant而不是在循环中访问工作簿。目前,如果我没有更改运行,它需要很长时间。对于这个问题,我缩短了我的代码,如果需要可以提供完整的代码。

我被困在这一行,thisArr(i - 1, 1) = thisArr(i - 1, 1) & "|" & sourceWS(i, readcols(j))

Public Sub generateIRandCRshocks(scenPath As String, scenNames() As Variant, curveNameToMarketData() As Variant, curveData() As Variant, curveNames() As Variant, currToRiskFree() As Variant, termBuckets() As Variant, exportPath As String)

Dim i As Long, j As Long
Dim thisScen As Long, thisCurve As Long, thisBucket As Long
Dim lastrow As String, thisRow As Long
Dim thisArr() As Variant
Dim thisArrRow As Long, thisCurveMapRow As Long, thisCurveDataRow As Long, thisRiskFreeRow As Long

Dim sourceWB As Variant
Dim sourceWS As String
Dim lastWSrow As Variant
Dim lastcol As String




    lastrow = lastWSrow(sourceWS) 
    lastcol = 20
    sourceWS = sourceWB.Worksheets(scenNames(thisScen, 1)).Range(Cells(1, 1), Cells(lastrow, lastcol))

  'read into array and concatenate attribute columns
    ReDim thisArr(1 To lastrow - 1, 1 To 4)
    For i = 2 To lastrow
        j = 1
            thisArr(i - 1, 1) = sourceWS(i, readcols(j))
        For j = 2 To 7
            thisArr(i - 1, 1) = thisArr(i - 1, 1) & "|" & sourceWS(i, readcols(j))
        Next j
        j = 8
            thisArr(i - 1, 2) = sourceWS(i, readcols(j))
        j = 9
            thisArr(i - 1, 3) = sourceWS(i, readcols(j))
        j = 2
            thisArr(i - 1, 4) = sourceWS(i, readcols(j)) 'currency entered again in its own column for easy lookup later
    Next i

1 个答案:

答案 0 :(得分:0)

ReadCols根本没有声明,SourceWS被定义为String而不是数组,就像你指的那样。

也许你的意思是:

Dim SourceWS as Variant, ReadCols as Variant

Dim SourceWS() as String, ReadCols() as String

如果要为数组分配工作表范围,则需要将其作为变体。

无关的观察:

这只是不必要地创建额外的代码行:

  j = 8
        thisArr(i - 1, 2) = sourceWS(i, readcols(j))

......而不仅仅是:

thisArr(i-1, 2) = sourceWS(i, readcols(8))