我试图动态定义行中的范围,例如ctrl + down或ctrl + shift + down(到下一个空白单元格),以与“ For Each itm In rng”语句一起使用。
最初,我将其设置为静态 set rng = Range(“ A4:A10”)
所以我试图将其更改为这样的
Dim rng As Range
Set rng = Range("A4").CurrentRegion.Rows.Count
For Each itm In rng
...
Next itm
我也尝试过类似的方法
Set StartCell = Range("A4")
rng = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
但是该代码似乎不适用于“ For r itng in rng”语句
非常感谢您的帮助。
答案 0 :(得分:0)
如果有帮助,请尝试以下方法:
Option Explicit
Sub Test()
Dim LastRow As Long 'to find the last row on your range
Dim MyRange As Range 'to reference the whole range
Dim C As Range 'to loop through your range
With ThisWorkbook.Sheets("MySheet") 'change MySheet for your sheet name
LastRow = .Cells(4, 1).End(xlDown).Row 'last row, how? You go down to the last row and then ctrl + up
Set MyRange = .Range("A4:A" & LastRow) 'dynamic range
For Each C In MyRange
'your code
Next C
End With
End Sub
答案 1 :(得分:0)
您可以使用.xlDown,相当于按Ctrl + Shift +向下键。
Dim rng As Range
Dim lastRow As Long
lastRow = Range("A4").End(xlDown).Row
Set rng = Range("A4:A" & lastRow)
For Each itm In rng
'do something
Next itm