根据条件excel vba隐藏行

时间:2015-02-13 19:30:51

标签: excel vba excel-vba hide

我有一个小的Excel宏,它通过一个大的名称列表,看看它是否在一个较小的列表中,如果是,它隐藏了整行。它不会抛出任何错误,但由于某种原因,它不会隐藏任何东西,我很困惑为什么。任何有关此问题的帮助将不胜感激!

Sub Filter()

Dim i As Long, rng1 As Range, rng2 As Range, j As Long

Set rng1 = Sheet6.Range("H2:H3")
Set rng2 = Sheet5.Range(Range("K2"), Sheet5.Range("K2").End(xlDown))

For i = 1 To rng2.Rows.Count

    For j = 1 To rng1.Rows.Count

        If rng2.Cells(i, 11).Value = rng1.Cells(j, 7).Value Then
            rng2.Cells(i, 11).EntireRow.Hidden = True
        End If

    Next j

Next i

End Sub

2 个答案:

答案 0 :(得分:0)

试试这个:

Set rng2 = Sheet5.Range("K2:" & Sheet5.Range("K2").End(xlDown).AddressLocal)

答案 1 :(得分:0)

正如用户3964076在评论中建议的那样,问题是像Range(“H2:H3”)。cells(2,11)这样的引用不会返回工作表第11列第二行的值,但是而是第十八列第三行的值。代码将H2视为范围中的第一个单元格,然后从那里移动另外的1行和10列。

请改为尝试:

Sub Filter()
  Dim i As Long, rng1 As Range, rng2 As Range, j As Long
  Set rng1 = Sheet6.Range("H2:H3")
  Set rng2 = Sheet5.Range(Range("K2"), Sheet5.Range("K2").End(xlDown))
  For i = 1 To rng2.Rows.Count
    For j = 1 To rng1.Rows.Count
      If rng2.Cells(i, 1).Value = rng1.Cells(j, 1).Value Then
        rng2.Cells(i, 1).EntireRow.Hidden = True
      End If
     Next j
  Next i
End Sub