Are there characters in my field or fields in my characters?

As I have said many times, Visio is far more than connected clip art. The shapes can have smarts. Parts of the shape can change by the use of shape data or control handles. It may be the geometry, colour or text. For now, I am going to talk about text.

Though there is only one text block in a shape, shapes can be grouped to contain several text blocks. Within the text block, you can have “Fields”, place holders for other bits of information.

These are some of the choices when you insert a field. It could relate to the size of the shape, shape data or page and document information. So, if you need a title block with name, date and other information, you create one shape and just drop it on the page. Title blocks are usually dropped on background page and the shape will reflect information about the foreground page, the background page is attached to,

Inserting a field is just a matter of selecting a location in the text and chose the [Field] button from the Text section of the Insert ribbon.

Of course, I do not have the artistic flair of Visio Guy, I prefer the mathematical precision of the formulas in the shapesheet, especially when I use the the power of VBA in Visio. The programming may sound intimidating, but Visio is one of the few VBA enabled Office apps that has a macro recorder. Before Microsoft acquired Visio in 2000, Visio was the first non Microsoft app to fully implement VBA. I was spoiled and I am now very rusty when it comes to Visio and C.

So, how do you add fields with VBA? This code will add the word “width”, the actual width of the shape and the page name to the text in the shape.

Sub Macro1()
Dim shp As Visio.Shape
Dim vsochar As Visio.Characters
Set shp = ActivePage.Shapes(1)
Set vsochar = shp.Characters
shp.Text = ""
vsochar.Begin = 0
vsochar.End = 0
vsochar.Text = "width "
Set vsochar = shp.Characters
vsochar.Begin = 6
vsochar.End = 6
vsochar.AddFieldEx visFCatGeometry, visFCodeWidth, visFmtNumGenNoUnits, 4105, 0
Set vsochar = shp.Characters
vsochar.Begin = 24
vsochar.End = 24
vsochar.AddFieldEx visFCatPage, visFCodePageName, visFmtStrNormal, 4105, 0
End Sub

Some things to note. You can start with no text, and the positon (the Begin, End) can be beyond the number of characters in the text, it will just add it to the end of what exists.

So, it is possible to create a shape purely by using VBA. I have done many projects where I spent more time in Excel getting the information organized and then just running VBA in Visio to use that information to build the shapes. I also spend a lot of time with the macro recorder exploring the VBA need to create various aspects of Visio shapes.
Case in point, this article is based on recently exploring with the macro recorder and the shapesheet to confirm what was happening.

I hope this helps.

John… Visio MVP in x-aisle

Published by johnvisiomvp

The original Visio MVP. I have worked with the Visio team since 1993