根据两个值取消隐藏行

时间:2018-05-24 12:40:58

标签: excel vba excel-vba

我写了VBA代码来隐藏我的图表中的行,在G列的单元格中,值为" XYZ"发生。

i = 4 ' row to begin with
j = Cells(i, 7).End(xlDown).Row
clmn = 7 ' column G
mark = False
For row = j To i Step -1
If (Cells(row, clmn).Value = "XYZ") Then
If mark Then
Union(Selection, Rows(row)).Select
Else
Rows(row).Select
mark = True
End If
End If
Next row
Selection.EntireRow.Hidden = True

这完全没问题。现在,在使用此修改图表之后,我想添加第二个附加的VBA代码,以便所有隐藏的行都带有" XYZ"只有在同一行的A列中出现" ABC"时,才会重新出现G列。因此,并非所有隐藏的行都应该取消隐藏。

如何修改自己的代码才能完成此操作?

2 个答案:

答案 0 :(得分:1)

你可以使用AutoFilter,如下所示:

Sub UnhideThem()
    Dim visbileRng As Range

    With Range("G3", Cells(Rows.Count, "A").End(xlUp)) ' reference columns A:G from row 3 (headers) down to column A last not empty row
        Set visbileRng = .SpecialCells(xlCellTypeVisible) ' store currently visible range
        .AutoFilter field:=1, Criteria1:="ABC" ' filter referenced range on its first column (i.e. "A") with value "ABC"
        .AutoFilter field:=7, Criteria1:="XYZ" ' filter referenced range on its 7th column (i.e. "A") with value "ABC"
        With .Resize(.Rows.Count - 1).Offset(1) ' reference "data" rows only (i.e skip "header" row)
            If CBool(Application.Subtotal(103, .Cells)) Then Set visbileRng = Union(visbileRng, .SpecialCells(xlCellTypeVisible)) 'if any filtered row in referenced range then add it to 'visbleRng'
        End With
        .Parent.AutoFilterMode = False ' remove filters
        .EntireRow.Hidden = True 'hide all referenced range rows
        visbileRng.EntireRow.Hidden = False ' unhide only rows to set visible
    End With
End Sub

答案 1 :(得分:0)

正如Redji评论一样,只需在If子句中添加一个条件即可。无论如何,我不喜欢使用union和select方法。

If Cells(row, clmn).Value = "XYZ" and  _
   Cells(row, 1).Value = "ABC" Then
   ' do the selection if you like
Selection.EntireRow.Hidden = false

您也可以使用特殊电池。例如,如果您的范围是A4:G& j您可以在图表中处理此代码。

range("a4:g" & j).Rows.SpecialCells(xlCellTypeVisible)

此致 中号