常量运行时错误"1004"



我试图将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

不能在工作表中选择未激活的区域,这就是导致错误的原因。

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

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

最新更新