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.
A simple thing to loop through selected cells and fill them with current date.
Ask if OK for cell that already has content.
These are the methods I use for the AutoFilter Method. I do not have any trouble dealing with one or more than one visible row and have no need to distinguish between the filter sets.
Set up your desktop so you can see both the worksheet and the VBE window. Open the VBE's Immediate window (Ctrl+G) so you can see the
Debug.Print
reporting. Put the cursor in thefilter_test
sub and start tapping F8 to walk through.Expected results from the VBE's Immediate window.