使用VBA在Excel中隐藏/取消隐藏特定对象

时间:2017-02-28 07:51:27

标签: excel vba excel-vba

我想要一个宏来隐藏/取消隐藏标注。

目的是让信息按钮一旦按下即可显示或隐藏信息标注。

问题是我有其他箭头和形状,我不想隐藏。

使用以下代码(1),我可以隐藏所有对象:

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

使用此代码(2),我可以隐藏/取消隐藏特定的标注形状

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

如何使用第一个代码(1)来运行标注形状,就像在第二个代码(2)中一样?

2 个答案:

答案 0 :(得分:3)

怎么样:

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

希望它有所帮助!

答案 1 :(得分:2)

由于visible属性是布尔值,因此可以缩短代码:

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

如何使用它:

Sub Test1_Selrac()
    InvertAllShapesVisibility ActiveSheet
End Sub

对于单一形状:

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

如何使用它:

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

对于包含关键字的多种形状:

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

如何使用它:

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