In a worksheet with data there is a column with an applied filter to limit the displayed data. The user selects 1 or more cells (not necessarily continuous) in a column and execute a VBA code. In the VBA code I'd like to iterate through selected cells and do some operations with them, but there is difference in Excel behavior when only 1 cell is selected (active in Excel terms). Code that works:
Sub Macro1()
If Selection.count = 1 Then
counter = 1
Debug.Print Selection.Text
Else
counter = Selection.SpecialCells(xlCellTypeVisible).count
For Each c In Selection.SpecialCells(xlCellTypeVisible)
Debug.Print c.Text
Next c
End If
Debug.Print counter
End Sub
QUESTION: Is there a way, more elegant and clean solution to do this? To get rid of If-Then?
Selection.SpecialCells(xlCellTypeVisible).count
generates overflow error if only one cell is activated (I think Excel expands selection to whole worksheet)
ActiveCell.Select
Selection.SpecialCells(xlCellTypeVisible).count
returns 2 if only one cell is selected (returns selected record twice)
EDIT Please note: filter is applied manually by the user not by the VBA code. Also user manually selects cells from filtered view and that selected cells are next used in VBA code.
.Rows.Count-1
...? Then looking at a single column ...? Try to avoidSelection
as a means of determining the range to be processed. In any event, it would beSelection.SpecialCells(xlCellTypeVisible).Count
notSelection.Count
. – user4039065