Set rng = ws.Range("A1", ws.Range("A1").End(xlDown))
For each cl in rng
获取运行时错误' 1004':
Application-defined or object-defined error in
**Set rng = ws.Range("A1", ws.Range("A1").End(xlDown))**
请帮忙
答案 0 :(得分:2)
我怀疑您没有Excel对象库的引用集,在这种情况下xlDown
没有值。使用:
Set rng = ws.Range("A1", ws.Range("A1").End(-4142))
或者,最好在模块的顶部定义常量:
Const xlDown as Long = -4142
答案 1 :(得分:1)
Rory已经告诉过你代码的主要问题是什么。
我建议你采用与你想要达到的目标略有不同的方法。
请注意,应尽可能避免使用xlDown
。考虑仅在单元格A1
中存在数据的情况。在这种情况下,xlDown
将选择整个Col A.另一种方法是在Col A中查找包含数据的最后一行,然后创建范围。
With ws
'~~> Find Last Row in Col A and then create the range
'~~> oXL is the Excel Application
If oXL.WorksheetFunction.CountA(.Cells) <> 0 Then
lastrow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lastrow = 1
End If
Set Rng = ws.Range("A1:A" & lastrow)
End With
并在顶部声明这个
Const xlPart As Long = 2
Const xlFormulas As Long = -4123
Const xlByRows As Long = 1
Const xlPrevious As Long = 2
如果您确定Col A中总会有数据,那么您也可以尝试这样做
lastrow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
Set Rng = ws.Range("A1:A" & lastrow)
并在顶部声明这个
Const xlUp As Long = -4162