宏仅在可见单元格上运行

时间:2016-08-10 13:28:03

标签: excel vba excel-vba macros

我想知道如何在可见(未隐藏)单元格上进行宏运行?  我应该在这段代码中添加什么:?

Dim cell As Range 

For Each cell In ActiveSheet.Cells.SpecialCells(xlCellTypeVisible) 
    With Application.FindFormat.Interior 
        .PatternColorIndex = xlAutomatic 
        .Color = 16711935 
        .TintAndShade = 0 
        .PatternTintAndShade = 0 
    End With 
    Cells.Find(What:="", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _ 
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _ 
    , SearchFormat:=True).Activate 
Next cell 
Exit Sub 

2 个答案:

答案 0 :(得分:1)

如果没有检查公式,您可以更改

ActiveSheet.Cells.SpecialCells(xlCellTypeVisible)

ActiveSheet.Cells.SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants)

或者如果它正在检查公式,请更改

ActiveSheet.Cells.SpecialCells(xlCellTypeVisible)

ActiveSheet.Cells.SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeFormulas)

这将使其无法在未隐藏的空白单元格上运行。

答案 1 :(得分:1)

这将激活所有可见的具有特定格式的单元格。

Sub Example()

    Dim SearchRange As Range
    Dim c As Range, FoundRange As Range
    Dim firstAddress As String

    On Error Resume Next

    Set SearchRange = ActiveSheet.UsedRange.SpecialCells(xlCellTypeVisible)

    On Error GoTo 0

    If Not SearchRange Is Nothing Then

        With Application.FindFormat.Interior
            .PatternColorIndex = xlAutomatic
            .Color = 16711935
            .TintAndShade = 0
            .PatternTintAndShade = 0
        End With

        Set c = SearchRange.Find(What:="", After:=SearchRange.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
                                 xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
              , SearchFormat:=True)

        If Not c Is Nothing Then
            firstAddress = c.Address
            Set FoundRange = c
            Do
                Set c = SearchRange.Find(What:="", After:=c, LookIn:=xlFormulas, LookAt:= _
                                         xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
                      , SearchFormat:=True)

                If Not c Is Nothing Then
                    'Do Something

                    Set FoundRange = Union(FoundRange, c)
                End If
            Loop While Not c Is Nothing And c.Address <> firstAddress

            FoundRange.Activate
        End If

    End If

End Sub