Reputation: 1
I have the below code to loop through each row of a selected range. However when only a single cell is selected, the code loops through each row in the worksheet rather than just dealing with the one instance.
What do I need to do so that the for loop only handles the one row when a single cell is selected?
Dim myRange as Range
Dim currRow as Range
Set myRange = Selection
For Each currRow In myRange.Rows.SpecialCells(xlCellTypeVisible)
MsgBox currRow.Address
Next currRow
Thanks,
Upvotes: 0
Views: 569
Reputation: 3279
Just add an if statement to the code to handle hidden rows:
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
Upvotes: 0
Reputation: 19737
I don't know the reason why the code behave as such. It looks ok.
But to get what you want, try this:
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
hope this works.
Upvotes: 1