给定多个范围,如果满足多个条件,则隐藏行

时间:2019-11-22 18:14:20

标签: excel vba

我正在尝试在这种情况下隐藏行:

#given some ranges within column B and C 
#for each row within the ranges 
#if the related cells in column B and C both have value equal to 0 
#then hide the specific row

这是我正在使用的代码,但是我正在努力实现两个单元格都必须具有value = 0的if部分

Sub HideRows()

Dim r0 As Range, r1 As Range, r2 As Range, MultiRange As Range, r As Range

Set r0 = Sheets("Sheet1").Range("B1:C6")
Set r1 = Sheets("Sheet1").Range("B8:C8")
Set r2 = Sheets("Sheet1").Range("B10:C11")
Set MultiRange = Union(r0, r1, r2)

For Each r In MultiRange
    r.EntireRow.Hidden = (r.Value = 0)
Next r

End Sub

1 个答案:

答案 0 :(得分:3)

您很近。实际上,您已经解决了较难的部分(联合范围)。将循环设置为在联合范围内的rows而非默认的cells

中移动
Sub HideRows()

Dim r0 As Range, r1 As Range, r2 As Range, MultiRange As Range, r As Range

Set r0 = Sheets("Sheet1").Range("B1:C6")
Set r1 = Sheets("Sheet1").Range("B8:C8")
Set r2 = Sheets("Sheet1").Range("B10:C11")
Set MultiRange = Union(r0, r1, r2)

For Each r In MultiRange.Rows
    r.EntireRow.Hidden = (r.Cells(1,1).value = 0 AND r.cells(1, 2).value = 0)
Next r

End Sub