恒定运行时错误' 1004'

时间:2012-09-14 15:56:29

标签: vba excel-2010

我正在尝试将3列中的数据逐一汇总并将下一页中的总数粘贴到三个单元格中。我提出了以下代码。它工作正常几次,但随后开始抛出错误:运行时错误'1004'应用程序定义或对象定义的错误。

Sub test1()

Dim Counter As Integer
Counter = 1

For i = 1 To 3

Do Until ThisWorkbook.Sheets("Sheet1").Cells(Counter, i).Value = ""

    ThisWorkbook.Sheets("Sheet1").Range(Cells(1, i), Cells(Counter, i)).Select
    Counter = Counter + 1

Loop

    Value1 = Application.WorksheetFunction.Sum(Selection)
    ThisWorkbook.Sheets("Sheet2").Cells(1, i).Value = Value1

Next i

End Sub

1 个答案:

答案 0 :(得分:1)

您无法在工作表中选择未激活的范围,即导致错误的范围。

如果除了Sheet1之外还有任何工作表,您的代码将抛出您列出的错误。 作为快速修复,在循环之前添加Thisworkbook.Sheets("Sheet1").Activate

作为更好的解决方案,您应该尝试从代码中选择。