Use VBA to add Text Field to a shape

Started by wapperdude, May 24, 2014, 01:46:54 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

wapperdude

#15
Why do I hear Yacine chuckling???

Well, decided to expand the little code snippet to show how to add multiple lines to be displayed in a shape.  Not just Field inserted text, but a mixture of regular shape text and field text.  Field text is more challenging because it has specific Visio defined formatting.  Yuck.  Yikes. 

Anyway, here's the code: 

Sub addFieldTxt()
    Dim shp As Visio.Shape
    Dim vChar1 As Visio.Characters
    Dim lstChr As Integer
   
    Set shp = ActiveWindow.Selection(1)
   
    If Not shp.SectionExists(visSectionTextField, False) Then
        shp.Characters.AddCustomFieldU Chr(34) & "NewFieldText" & Chr(34), visFmtNumGenNoUnits
    End If
       
'The next 2 sections show two methods of adding additional lines.
'Both lines show the same info:  the name of the shape.
'The 1st use text entry, the 2nd uses AddFieldEx

        lstChr = Len(shp.CellsSRC(visSectionTextField, 0, visFieldValue).ResultStr(visNone))
        Set vChar1 = shp.Characters
        vChar1.Begin = lstChr           'sets reference at end of string
        vChar1.End = lstChr
        vChar1.Text = "" & Chr(10) & "" 'sets new line
        vChar1.Begin = lstChr + 1       'sets reference at beginning of new line
        vChar1.End = lstChr + 1
        vChar1.Text = shp.Name          'adds shape name on the 2nd line as normal shape text
       
        lstChr = lstChr + 1 + Len(shp.Name)
        vChar1.Begin = lstChr           'increments to end of 2nd line
        vChar1.End = lstChr
        vChar1.Text = "" & Chr(10) & ""
        vChar1.Begin = lstChr + 1
        vChar1.End = lstChr + 1
'This next line adds the shape name as Field Text:
        vChar1.AddFieldEx visFCatObject, visFCodeObjectName, visFmtStrNormal, 1033, 0
   
End Sub
Visio 2019 Pro