Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel VBA-如何根据特定条件隐藏行?_Excel_Vba - Fatal编程技术网

Excel VBA-如何根据特定条件隐藏行?

Excel VBA-如何根据特定条件隐藏行?,excel,vba,Excel,Vba,如果B列的值为“x”,我将尝试隐藏所有行。这就是我到目前为止所做的: Public Sub HideRowsOOS() Application.ScreenUpdating = False With ActiveSheet For Each cell In Range("B2:B") If cell.Value = "x" Then cell.EntireRow.Hidden = True End If

如果B列的值为“x”,我将尝试隐藏所有行。这就是我到目前为止所做的:

Public Sub HideRowsOOS()

    Application.ScreenUpdating = False

    With ActiveSheet
    For Each cell In Range("B2:B")
        If cell.Value = "x" Then
            cell.EntireRow.Hidden = True
        End If
    Next cell

    Application.ScreenUpdating = True
End Sub
替换:

Range("B2:B")
与:


(您也可以使用语句删除

我将提供以下优化过程:

Option Explicit

Public Sub HideRowsOOS()

    Application.ScreenUpdating = False

    With Worksheets("mySheet") 'change as neeeded

        Dim lastRow as Long
        lastRow = .Cells(.Rows.Count,2).End(xlUp).Row

        For Each cell In .Range("B2:B" & lastRow)

            If cell.Value = "x" Then 

                Dim collect as Range
                If collect Is Nothing Set collect = cell: Else Set collect = Union(collect, cell)

            End If

        Next cell

    End With

    collect.EntireRow.Hidden = True

End Sub

“B2:B”不是有效的范围参考。通常的方法是将其包含在您的参考中。请注意,您不是指使用ActiveSheet的
。。。您需要在
范围
调用前面添加句点
,才能真正执行此操作。为了清楚起见,
.UsedRange
如果单元格显示为空白,但在没有数据的区域中设置了内部格式,则可能会产生意外的后果并显著影响性能。@ScottHoltzman您是对的。该建议可能不必要地测试一些额外的单元格,但它比测试整个B列要好
Option Explicit

Public Sub HideRowsOOS()

    Application.ScreenUpdating = False

    With Worksheets("mySheet") 'change as neeeded

        Dim lastRow as Long
        lastRow = .Cells(.Rows.Count,2).End(xlUp).Row

        For Each cell In .Range("B2:B" & lastRow)

            If cell.Value = "x" Then 

                Dim collect as Range
                If collect Is Nothing Set collect = cell: Else Set collect = Union(collect, cell)

            End If

        Next cell

    End With

    collect.EntireRow.Hidden = True

End Sub