[英]Get column x's Cells from a Range of Cells in Excel VBA
I have a Range of Cells, let's say: Range("A1:D20") which is stored in a Range variable. 我有一个单元格范围,比方说:存储在Range变量中的Range(“ A1:D20”)。 In my case, the range is actually a named range.
就我而言,范围实际上是一个命名范围。 Eg
例如
Set rngList = Range("LIST")
I'm trying to use a 'for each' loop to traverse only the Cells in column 2. EDIT: this is a relative reference, not absolute: 2nd column of the range. 我正在尝试使用“ for each”循环仅遍历第2列中的单元格。编辑:这是一个相对参考,而不是绝对的:范围的第二列。
Eg 例如
for each rngCell in rngList.Columns(2)
//Do stuff
next
The .Columns(2) doesn't work. .Columns(2)不起作用。 Is there a simple way to do this?
有没有简单的方法可以做到这一点?
Cheers 干杯
Add .Cells
after .Columns(2)
: 在
.Columns(2)
之后添加.Cells
:
For Each rngCell In Range("LIST").Columns(2).Cells
Debug.Print rngCell
Next
You could create another range directly from your existing range using column B (efficient), or you could just check if each cell in your existing range is in column 2, before doing your stuff: 您可以使用B列(有效)直接从现有范围中创建另一个范围,也可以在进行填充之前检查现有范围中的每个单元格是否在第2列中:
Method 1 (create a derivative range): 方法1(创建一个导数范围):
Sub method1()
Dim rngList As Range
Dim rngList2 As Range
Set rngList = Range("LIST")
Set rngList2 = Range("B" & rngList.Row, Range("B" & (rngList.Row + rngList.Rows.Count - 1)))
For Each rngCell In rngList2
rngCell.Value = "hey1"
Next rngCell
End Sub
Method 2 (check if cell is in column 2): 方法2(检查单元格是否在第2列中):
Sub method2()
Dim rngList As Range
Set rngList = Range("LIST")
For Each rngCell In rngList
If rngCell.Column = 2 Then
rngCell.Value = "hey2"
End If
Next rngCell
End Sub
try this 尝试这个
For Each rngCell In Intersect(rngList, rngList.Parent.Columns(2))
' //Do stuff
Next
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.