在循环选定范围的行时处理单个单元格

时间:2013-10-02 06:30:12

标签: excel vba excel-vba for-loop row

我有以下代码来遍历所选范围的每一行。但是,当只选择一个单元格时,代码会循环遍历工作表中的每一行,而不仅仅是处理一个实例。

我需要做什么才能使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

谢谢,

2 个答案:

答案 0 :(得分: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
希望这有效。

答案 1 :(得分:0)

只需在代码中添加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