I am creating a series of ActiveX labels for two categories of information in a Microsoft Word VBA script. The categories of information are: Fiscal year (FY) and Contract Yield (CY). I am creating the labels to be placed within designated cells of a series of tables. I want to change the names of the labels to match up with their category. For example, label1 would be named to FY1. I need to change the names of these labels so they could eventually match up with data in an Excel spreadsheet.
I am getting stuck at the renaming portion (ActiveDocument.Label1.Name = "FY").
Dim num As Integer
Dim TableNo As Integer
Dim seq As Integer
TableNo = ActiveDocument.Tables.Count
num = 4
seq = 1
'' Labels for "FY"
Do
ActiveDocument.Tables(num).cell(6, 2).Range.InlineShapes.AddOLEControl ClassType:="Forms.Label.1"
ActiveDocument.Label1.Name = "FY"+ seq
seq = seq + 1
num = num + 1
Loop Until num = TableNo + 1
'''Next Group of labels for "CY"
num = 4
seq = 1
Do
ActiveDocument.Tables(3).cell(8, 2).Range.InlineShapes.AddOLEControl ClassType:="Forms.Label.1"
ActiveDocument.Label1.Name = "CY"+ seq
seq = seq + 1
num = num + 1
Loop Until num = TableNo + 1
There is a related article but I can't see how the examples would relate.
** My labels will be inserted in the 4th table of the document, which is why I used num = 4.
ActiveX controls were developed for use in VBA UserForms. Making them capable of insertion on an Office documents surface was something of an after-thought. Enabling the UserForm behavior involves some "magic" on the part of Word.
On a Word document's surface, an ActiveX control is managed through a Control
field, which can be seen by pressing Alt+F9 to toggle field codes on. The AddOLEControl
method generates the field and hooks up the plumbing, so to speak.
But as far as Word is concerned, it doesn't "see" the ActiveX control, it works with the field code and displays the field result, which is an image, either a member of the InlineShapes
or the Shapes
collection.
When communicating with an ActiveX control on the document surface it's therefore necessary to work through the graphic object in order to get to the "real control".
The following sample code illustrates - just substitute the Range
you need to work with for Selection.Range
(used for simplicity and to make the code sample accessible to all reading this Q&A).
The AddOLEControl
method is run on the InlineShapes
collection, so it returns an InlineShape
object. A MSForms.Label
object is set to the InlineShape's OLEFormat.Object
- this is what provides the connection to the control's programming interface. Through that, it's possible to access the properties such as are found in the Properties Window for the control.
Sub InsertRenameActiveX()
Dim ctl As MSForms.Label
Dim ils As Word.InlineShape
Set ils = Selection.Range.InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
Set ctl = ils.OleFormat.Object
ctl.Name = "FY" & "3"
ctl.Caption = "test"
End Sub