简体   繁体   English

Excel VBA:使用循环过滤(隐藏)数组

[英]Excel VBA: Filter (hide) Array using loop

Im still a beginner when it comes to VBA and I'm trying to write a code that hides rows if its cell value equals zero and the user has chosen to set another cell value to the correct wording. 对于VBA,我还是一个初学者,我正在尝试编写一个代码,如果其单元格值等于0并且用户选择将另一个单元格值设置为正确的措辞,则该行将隐藏行。 However, the code I wrote doesn't seem to work; 但是,我编写的代码似乎无效。 I'm sure I have forgotten to add something or am missing some key element but can't seem to figure out what it is. 我确定我已经忘记添加某些内容或缺少一些关键元素,但似乎无法弄清楚它是什么。

I have posted my code below. 我已经在下面发布了我的代码。 Any help would be much appreciated. 任何帮助将非常感激。

Sub HideEmptyRows()

Application.EnableEvents = False

Worksheets("Filtered Data").Rows("7:600").EntireRow.Hidden = False

If Range("J7") = "Filter" Then

    For Each cell In Range("J10:J503")
        If cell.Value = 0 Then
            cell.EntireRow.Hidden = True
        End If
    Next cell

Application.EnableEvents = True

End Sub

Consider: 考虑:

Sub HideEmptyRows()
    Application.EnableEvents = False
    With Worksheets("Filtered Data")
        .Rows("7:600").EntireRow.Hidden = False

        If .Range("J7") = "Filter" Then
            For Each cell In .Range("J10:J503")
                If cell.Value = 0 Then
                    cell.EntireRow.Hidden = True
                End If
            Next cell
        End If

    End With
    Application.EnableEvents = True
End Sub

NOTE: 注意:

  1. used With 使用With
  2. small clean-up to the logic 逻辑上的小清理
  1. You don't test to see whether there actually exists a worksheet named "Filtered Data" . 您无需测试是否实际上存在一个名为"Filtered Data"的工作表。

  2. You unhide rows in Worksheets("Filtered Data") but then you check values and hide rows in whatever sheet happens to be the ActiveSheet . 您取消隐藏Worksheets("Filtered Data")行,但是随后检查值并在碰巧是ActiveSheet任何工作表中隐藏行。

  3. You did not declare the variable cell . 您没有声明变量cell Option Explicit is a good friend; Option Explicit是个好朋友; use it. 用它。

  4. There is a missing End If . 缺少End If

Otherwise the code works; 否则,代码会起作用; tested like this: 像这样测试:

Option Explicit

Sub HideEmptyRows()

  Dim cell As Range

  Application.EnableEvents = False

  With Worksheets("Filtered Data")
    .Rows("7:600").EntireRow.Hidden = False
    If .Range("J7") = "Filter" Then
      For Each cell In .Range("J10:J503")
        If cell.Value = 0 Then
          cell.EntireRow.Hidden = True
        End If
      Next cell
    End If
  End With

  Application.EnableEvents = True

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM