Sub copyNonblankData()
Dim erow As Long, lastrow As Long, i As Long
lastrow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrow
If Sheet1.Cells(i, 1) <> "" Then
' i'm assuming the next line is the 8th line?
Sheets("Sheet1").Range(Cells(i, 1), Cells(i, 2)).Copy
Sheets("Sheet2").Activate
' error occurs here
erow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Row.Offset(1, 0).Row
ActiveSheet.Paste Destination:=Sheets("Sheet2").Range(Cells(erow, 1), Cells(erow, 2))
Sheets("Sheet1").Activate
End If
Next i
Application.CutCopyMode = False
End Sub
最佳答案
Excel VBA 中的 Offset 属性采用范围,即远离特定范围的特定行数和列数。
Sheet2.Cells(Rows.Count, 1).End(xlUp).Row
将为您提供 Long
而不是 Range Object
.
你的代码可以写成
Dim rng As Range
Set rng = Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
erow = rng.Row
或者简单地作为
erow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Row + 1
如果相关工作表处于事件状态,您的代码也将起作用。您需要完全限定您的单元格,如 Why does Range work, but not Cells? 中所示。
提示
如果您使用CodeName
,则使用CodeName
,并避免使用工作表的Name
。如果您使用 Name
,请避免使用 Codename
。你最终会感到困惑。如果您不知道它们之间的区别,那么您可能想查看Refer to sheet using codename
请记住,如果代号不存在,您将再次收到相同的错误(需要对象
)。顺便说一句,如果工作表的名称不存在,那么您将收到不同的错误(下标超出范围
)。
因此,如果 erow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Row + 1
给出相同的错误,则意味着 Sheet2
不会不存在。尝试使用
erow = Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row + 1
关于excel - 在调试 VBA 代码时,我在保存“第 8 行需要对象”时遇到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59351206/