【问题标题】:Handle a single cell when looping through rows of a selected range循环遍历选定范围的行时处理单个单元格
【发布时间】:2013-10-02 06:30:11
【问题描述】:
我有下面的代码循环遍历选定范围的每一行。但是,当只选择一个单元格时,代码会遍历工作表中的每一行,而不是只处理一个实例。
我需要怎么做才能让 for 循环在选择单个单元格时只处理一行?
Dim myRange as Range
Dim currRow as Range
Set myRange = Selection
For Each currRow In myRange.Rows.SpecialCells(xlCellTypeVisible)
MsgBox currRow.Address
Next currRow
谢谢,
【问题讨论】:
标签:
vba
excel
for-loop
row
【解决方案1】:
我不知道代码为什么会这样。看起来不错。
但要得到你想要的,试试这个:
Dim myRange As Range
Dim currRow As Range
Set myRange = Selection
If myRange.Rows.count = 1 And myRange.Columns.count = 1 Then
For Each currRow In myRange.Rows
MsgBox currRow.Address
Next currRow
Else
For Each currRow In myRange.Rows.SpecialCells(xlCellTypeVisible)
MsgBox currRow.Address
Next currRow
End If
希望这行得通。
【解决方案2】:
只需在代码中添加一个 if 语句来处理隐藏行:
Dim myRange As Range
Dim currRow As Range
Set myRange = Selection
For Each currRow In myRange
If currRow.EntireRow.Hidden = False Then
'Place your code here.
Debug.Print currRow.Address
End If
Next currRow