过滤基于行的复选框

时间:2017-03-10 19:20:11

标签: excel excel-vba vba

我有一些VBA代码,我打算用它来过滤而不是。我有一些问题,虽然我似乎无法解决,但此时我已经困惑了。

Sub FilterRow()
    Dim b As Object, cs As Integer
    Set b = ActiveSheet.CheckBoxes(Application.Caller)
    With b.TopLeftCell
        cs = .Row
    End With

    Dim rng As Range, cel As Range, totalRng As Range
    If ActiveSheet.AutoFilterMode = True Then
        ActiveSheet.AutoFilterMode = False
    End If

    For Each cel In totalRng
        If cel.Row <> cs Then
            cel.EntireColumn.Hidden = True
        Else
            cel.EntireColumn.Hidden = False
        End If
     Next cel

End Sub

目标是让代码检查某个值的特定 C:DX,如果值 NOT 然后隐藏该列。最终消除该特定行中的任何空白单元格。

1 个答案:

答案 0 :(得分:0)

因此,假设FilterRow是您已分配给复选框的宏,以下将执行我认为您尝试执行的操作:

Sub FilterRow()
    Dim b As Object, cs As Integer
    Set b = ActiveSheet.CheckBoxes(Application.Caller)

    With b.TopLeftCell
      cs = .row
    End With

    Dim rng As Range, cel As Range, totalRng As Range
    Set totalRng = Range("C" & cs & ":DX" & cs)

    If b.Value = 1 Then
      If ActiveSheet.AutoFilterMode = True Then
         ActiveSheet.AutoFilterMode = False
      End If

      For Each cel In totalRng
         If cel.Value = "" Then
            cel.EntireColumn.Hidden = True
         Else
            cel.EntireColumn.Hidden = False
         End If
      Next cel
    Else
      ' Set up autofilter here
      totalRng.EntireColumn.Hidden = False
    End If

End Sub

由于在选中或取消选中复选框时会触发此宏,因此我更改了逻辑,以便在取消选中复选框时取消隐藏所有列(即撤消选中时所执行的操作)。