简体   繁体   中英

Hide/unhide specific objects in Excel with VBA

I want to have a macro to hide/unhide callouts.

The intention is to have an information button that once presses show or hide the information callouts.

The problem is that I have other arrows and shapes that I don't want to be hidden.

With the following code (1) I can hide all objects:

Dim sObject As Shape
For Each sObject In ActiveSheet.Shapes
    If sObject.Visible = False Then
        sObject.Visible = True
    Else
        sObject.Visible = False
    End If
Next

And with this code (2) I can hide/unhide specific callout shapes

If ActiveSheet.Shapes("Rectangular Callout 6").Visible = False Then
    ActiveSheet.Shapes("Rectangular Callout 6").Visible = True
Else
    ActiveSheet.Shapes("Rectangular Callout 6").Visible = False
End If

How can I have the first code (1) to run through the callout shapes only like in the second code (2)?

How about:

Dim sObject As Shape
For Each sObject In ActiveSheet.Shapes
   If Not InStr(sObject.Name, "Callout") = 0 Then sObject.Visible = Not sObject.Visible
Next sObject

Hope it helps!

As the visible property is a boolean, you can shorten your code :

Sub InvertAllShapesVisibility(wS As Worksheet)
    Dim sObject As Shape
    '''Invert visibility of all shapes
    For Each sObject In wS.Shapes
        sObject.Visible = Not sObject.Visible
    Next sObject
End Sub

How to use it :

Sub Test1_Selrac()
    InvertAllShapesVisibility ActiveSheet
End Sub

And for a single shape :

Sub RevertShapeVisibility(wS As Worksheet, ShapeName As String)
    Dim sObject As Shape
    '''Invert visibility of all shapes containing the KeyWord
    For Each sObject In wS.Shapes
        If sObject.Name = ShapeName Then sObject.Visible = Not sObject.Visible
    Next sObject
End Sub

How to use it :

Sub Test2_Selrac()
    RevertShapeVisibility ActiveSheet, "Rectangular Callout 6"
End Sub

And for multiple shapes containing keywords :

Sub RevertCalloutsVisibility(wS As Worksheet, KeyWord As String)
    Dim sObject As Shape
    '''Invert visibility of one shape
    For Each sObject In wS.Shapes
        If Instr(1,sObject.Name,KeyWord) Then sObject.Visible = Not sObject.Visible
    Next sObject
End Sub

How to use it :

Sub Test3_Selrac()
    RevertCalloutsVisibility ActiveSheet, "Rectangular Callout"
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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