Excel:运行时错误'1004'将VBA数组分配给Range而不事先调用Worksheet.Activate

时间:2013-04-24 15:08:48

标签: excel excel-vba excel-2010 dynamic-arrays vba

我在2d VBA动态数组中生成一个大的双精度矩阵。当我尝试将Array分配给Excel Range对象时,收到以下错误:

Runtime Error '1004':

Application-defined or Object-defined Error

除非,即在分配之前我调用Worksheet.Activate。 (阵列的大小约为88 x 1150) 这是代码片段:

Dim lIndxRow As Long, lIndxRowBase As Long, lIndxRowLast As Long, lIndxCol As Long, lIndxColBase As Long, lIndxColLast As Long
lIndxRow = [Close_FirstRow]
lIndxRowBase = [Close_FirstRow]
lIndxRowLast = [Close_LastRow]
lIndxColBase = [Close_FirstCol]
lIndxColLast = [Close_LastCol]

Dim Mat() As Double
ReDim Mat(lIndxRowBase To lIndxRowLast, lIndxColBase To lIndxColLast + 1)


While lIndxRow <= lIndxRowLast
    nSharesTotal = 0#
    While lIndxCol <= lIndxColLast
        Dim nShares As Double
        '
        ' Calculate value for nShares
        '
        Mat(lIndxRow, lIndxCol) = nShares
        nSharesTotal = nSharesTotal + nShares
        lIndxCol = lIndxCol + 1
    Wend
    Mat(lIndxRow, lIndxCol) = nSharesTotal
    lIndxRowPrev = lIndxRow
    lIndxRow = lIndxRow + 1
Wend
' no error when next line uncommented
'Worksheets("Share Pos").Activate
Worksheets("Share Pos").Range(Cells(lIndxRowBase, lIndxColBase), Cells(lIndxRowLast, lIndxColLast + 1)).Value2 = Mat

1 个答案:

答案 0 :(得分:2)

问题是单元格对象不是完全限定的。你必须完全符合他们的资格。试试这个(在CELLS之前注意DOT?

With Worksheets("Share Pos")
    .Range(.Cells(lIndxRowBase, lIndxColBase), .Cells(lIndxRowLast, _
    lIndxColLast + 1)).Value2 = Mat
End With