Search code examples
vbadynamicms-wordreal-timeactivexobject

Changing ActiveX Component Name Properties Dynamically in Word


I am trying to develop a dynamic user form in a Word document that will create an ActiveX radio button with a generic name and then rename that created radio button to make it have a specific number based on its location in the form.

So far I believe I have all the components to write the code because I am able to create the button. I create the button by using VBA to import a quick part that has the radio button with a defined radioButtonX name and I am able to change the name property of that radio button to radioButton1 for example. The problem that I am running into is that my code will insert the quick part with the generic radioButtonX name and then fail to change the radio button name because it says that radioButtonX does not exist. However, I can manually run the second part of the code after radioButtonX has been inserted and I am able to successfully change the radio button name giving me the end result that I am looking for in two separate steps.

I am a self taught VBA scripter for the last year so I am far from an expert at coding. A few of the strategies that I have taken so far were to:

  • Put in waits (thinking that pausing the script would give the script time to recognize the new radio button)
  • Separated the code into different subs having one sub create the radio button and then call a sub to change the name (hoping this would update VBA)
  • Separated the code into different modules having one modules create the radio button and then call a modules to change the name (hoping this would update VBA)

I was hoping for some advice, strategies, or sample codes that I can use to get VBA to recognize the new radio button that I have inserted while the code was running. Another thought that I had was maybe there is a command that exists that will have VBA refresh its knowledge of variables, but I have not have any luck finding something like that in my web searches to this point.


Solution

  • I tried to simplify the code that I was working on and pull out the code that would perform the function that I was requesting. Running the simpler code was successful and listed below.

    Private Sub AddRadioButton() 
        Selection.TypeText Text:="TestRadioButton" 
        Selection.Range.InsertAutoText 
        ActiveWindow.View.ShowXMLMarkup = wdToggle 
    
        ChangeButtonName 
    End Sub 
    
    Private Sub ChangeButtonName() 
        ThisDocument.radioButtonX.Name = "radioButton1" 
    End Sub 
    

    For this script to work you must create a quick part or a radio button that is named TestRadioButton. I think now the root issue has to deal with timing that looked like it wasn't working because the script that this code came from is using a quick part with multiple generic radio buttons in it so the script executing does not recognize the new radio buttons while running.