Hello
Someone will answer this in about a second...
I want to refer to a named shape in the ActivePage, but I want my code to handle when the shape gets automatically deleted / renamed etc. So something like
If IsError(ActivePage.Shapes("MyShape")) Then
' ... do something
Else
' ... do something else
End If
But this doesn't work. What syntax should I be using?
Many thanks
Hi StevieP,
There's no nice ShapeExists function, so you can either loop through all the shapes (which can be a pain due to nested groups), or just trap the error.
Here's the VBA:
Public Function GetShapeByName(name As String, pg As Visio.Page) As Visio.Shape
On Error GoTo Err
Set GetShapeByName = pg.Shapes(name)
Exit Function
Err:
Set GetShapeByName = Nothing
Exit Function
End Function
Sub Test()
'// Draw two rectangles on a blank page. By default, they
'// will have names of "Sheet.1" and "Sheet.2"
'// Add text to the shapes: "one", "two"
Dim shp As Visio.Shape
Set shp = GetShapeByName("Sheet.1", Visio.ActivePage)
If Not (shp Is Nothing) Then Debug.Print shp.Text
Set shp = GetShapeByName("Sheet.2", Visio.ActivePage)
If Not (shp Is Nothing) Then Debug.Print shp.Text
Set shp = GetShapeByName("Sheet.3", Visio.ActivePage)
If Not (shp Is Nothing) Then Debug.Print shp.Text
'// Your output should look like this:
'// one
'// two
'//
'// 'three' doesn't exist, so you won't see it in the output
End Sub
VB.NET is nicer, due to the Try/Catch block that can be used.
Public Function GetShapeByName(name As String, pg As Visio.Page) As Visio.Shape
Try
Return pg.Shapes(name)
Catch
Return Nothing
End Try
End Function
Sub Test()
'// Draw two rectangles on a blank page. By default, they
'// will have names of "Sheet.1" and "Sheet.2"
'// Add text to the shapes: "one", "two"
Dim shp As Visio.Shape
Set shp = GetShapeByName("Sheet.1", Visio.ActivePage)
If Not (shp Is Nothing) Then Debug.WriteLine(shp.Text)
Set shp = GetShapeByName("Sheet.2", Visio.ActivePage)
If Not (shp Is Nothing) Then Debug.WriteLine(shp.Text)
Set shp = GetShapeByName("Sheet.3", Visio.ActivePage)
If Not (shp Is Nothing) Then Debug.WriteLine(shp.Text)
'// Your output should look like this:
'// one
'// two
'//
'// 'three' doesn't exist, so you won't see it in the output
End Sub
Note, this technique is best used when you expect to get a shape most of the time, ie: the shape not being there is the exception. If you are "not finding shapes" many times per second, your computer will be quite busy, because exception handling is computationally expensive. Depends on your application, of course.