VBA,Excel – 遍历在过滤列中select的单元格

在包含数据的工作表中,有一个带有应用filter的列来限制显示的数据。 用户在列中select一个或多个单元格(不一定是连续的)并执行VBA代码。 在VBA代码中,我希望遍历选定的单元格,并对它们进行一些操作,但是当仅select一个单元格(Excel中有效)时,Excel的行为会有所不同。 代码工作:

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 

问题:有没有一种方法,更优雅和干净的解决scheme来做到这一点? 为了摆脱If-Then?

 Selection.SpecialCells(xlCellTypeVisible).count 

如果只激活一个单元格,则会生成溢出错误(我认为Excel将select扩展到整个工作表)

 ActiveCell.Select Selection.SpecialCells(xlCellTypeVisible).count 

返回2,如果只有一个单元格被选中(返回选定的logging两次)

编辑请注意:filter是由用户手动应用而不是由VBA代码。 另外,用户从过滤的视图中手动select单元格,然后在VBA代码中使用所选的单元格。

以下是基于这个示例数据。

  Column A Column A Column C abc 1 AA-01 BB-01 1 2 AAA-02 BBB-02 2 3 AAAA-03 BBBB-03 2 

这些是我用于AutoFilter方法的方法 。 我没有任何问题处理一个或多个可见的行,并且不需要区分filter组。

 Sub filter_test() With Worksheets("Sheet16") '<~~set this properly If .AutoFilterMode Then .AutoFilterMode = False With .Cells(1, 1).CurrentRegion .AutoFilter field:=3, Criteria1:=1 'report on column A With .Resize(.Rows.Count - 1, 1).Offset(1, 0) If CBool(Application.Subtotal(103, .Cells)) Then reportVisibleCells visRng:=.Cells Else Debug.Print "no visible cells with 1" End If End With .AutoFilter field:=3 .AutoFilter field:=3, Criteria1:=2 'report on column B With .Resize(.Rows.Count - 1, 1).Offset(1, 1) If CBool(Application.Subtotal(103, .Cells)) Then reportVisibleCells visRng:=.Cells Else Debug.Print "no visible cells with 2" End If End With .AutoFilter field:=3 .AutoFilter field:=3, Criteria1:=3 'report on column C With .Resize(.Rows.Count - 1, 1).Offset(1, 2) If CBool(Application.Subtotal(103, .Cells)) Then reportVisibleCells visRng:=.Cells Else Debug.Print "no visible cells with 3" End If End With .AutoFilter field:=3 End With If .AutoFilterMode Then .AutoFilterMode = False End With End Sub Sub reportVisibleCells(visRng As Range) Dim vr As Range With visRng.SpecialCells(xlCellTypeVisible) For Each vr In .Cells Debug.Print vr.Text Next vr Debug.Print .Count End With End Sub 

设置您的桌面,以便您可以看到工作表和VBE窗口。 打开VBE的立即窗口(Ctrl + G),以便您可以看到Debug.Print报告。 将光标放在filter_test子文件中,并开始点击F8进行浏览。

VBE立即窗口的预期结果。

 AA-01 1 BBB-02 BBBB-03 2 no visible cells with 3