确定最后一个活动行

时间:2018-07-09 15:35:23

标签: excel vba excel-vba

大家好,我想做一个宏来隐藏每一行,在E列中有一个0,这样我就只能在其中包含数据的行。

Sub Hide_Columns_Containing_Value()
'Description: This macro will loop through a row and
'hide the column if the cell in row 1 of the column
'has the value of X.
'Author: Jon Acampora, Excel Campus
'Source:

Dim c As Range

    For Each c In Range("E5:E15").Cells
        If c.Value = "0" Then
            c.EntireRow.Hidden = True

            'You can change the property above to False
            'to unhide the columns.
        End If
    Next c

End Sub

这是我发现的内容,但我希望它遍历整个列直到空白,不仅是范围,因为范围的大小每次都会改变 谢谢您的时间和答复!

2 个答案:

答案 0 :(得分:3)

您可以使用Union来收集合格的行并一口气藏起来。

Option Explicit
Sub Hide_Columns_Containing_Value()
    Dim c As Range, unionRng As Range

    For Each c In Range("E5:E15").Cells
        If c.Value = "0" Then
            If Not unionRng Is Nothing Then
                Set unionRng = Union(unionRng, c)
            Else
                Set unionRng = c
            End If
        End If
    Next c
    If Not unionRng Is Nothing Then unionRng.EntireRow.Hidden = True
End Sub

答案 1 :(得分:1)

您的问题不是“如何隐藏具有0的行”,您的代码已经可以使用了。
您的问题标题应该为如何找到ActiveRange

提出正确的问题有助于您更快地找到更好的解决方案。

Dim ws as WorkSheet: Set ws = Sheets("Sheet1")
Dim lr as Long
lr = ws.Cells(Rows.Count, "E").End(xlUp).Row

For each cell in ws.Range(ws.Cells(5, "E"), ws.Cells(lr, "E"))
   If cell = 0 Then
      cell.EntireRow.Hidden = True
   End If
Next cell
  

用您的SheetName替换Sheets("Sheet1")