我正在关注问题How to avoid using Select in Excel VBA macros的建议,但仍然得到"Application-defined or object-defined error" .
我的宏假设要检查其中一行中的值,将其与设置值进行比较,如果值等于,则将行复制到另一个工作表 . 我试图避免使用.Select命令,但无论我尝试什么,我都会收到错误 .
这是我的最后一个版本:
Counter2 = 17
For Counter1 = 12 To 150
Dim S As Worksheet
Dim R As Worksheet
Dim SL As Range
Dim RL As Range
Set R = Sheets("Front")
Set S = Sheets("CHECK LIST")
Set SL = S.Range(Cells(Counter1, 1), Cells(Counter1, 10))
Set RL = R.Range(Cells(Counter2, 1), Cells(Counter2, 10))
Set curCell = Worksheets("CHECK LIST").Cells(Counter1, 6)
Set checkCell = Worksheets("Front").Cells(3, 5)
If curCell.Value = checkCell.Value Then
With S
.SL.Copy
End With
With R
.RL.PasteSpecial
End With
Counter2 = Counter2 + 1
End If
Next Counter1
这是否与Range中变量(Counter1,Counter2)的使用有关?
1 回答
错误可能是由此代码块中的
Copy
和PasteSpecial
行引起的:一旦有
Set
范围变量,Excel就知道哪个工作表和哪个工作簿包含该范围变量 . 如果您想对该范围执行某些操作,则无需包含工作表 . 因此,在您的代码中,您只需使用考虑一下你应该在外面的循环中是否有任何代码总是一个好主意 . 在你的代码中,你循环中的工作表变量,但这应该在循环之前完成一次 . 添加对帖子的评论,您的代码应更改为:
PasteSpecial
方法有几个参数:如果您不使用这些,那么也许您可以进行“正常”复制和粘贴?