I am trying to automate a Word file with a userform.
I was thinking to have some variables in the Word file and to put a button in the ribbon that opens a userform to input these values.
I followed some tutorial I found online and I have the following code when I press OK on the userform:
Private Sub cmdOK_Click()
Set oVars = ActiveDocument.Variables
Hide
oVars(RfQ).Value = TextBox1.Value
oVars(SFDC).Value = TextBox2.Value
ActiveDocument.Fields.Update
Unload.Me
End Sub
I get the error
"Compile Error, Variable not defined".
In my text I have the following: {DOCVARIABLE SFDC * MERGEFORMAT}
My aim is to fill the variables with the value I input in the userform.
Further to this, I would like that every time I open the userform from the ribbon I get pre filled the information that is in the variable and that I can change/update them.
The first time you will have to add the variable, like this:
oVars.Add "RfQ", TextBox1.Value
Once it is created, you can change it like this:
oVars("RfQ") = TextBox1.Value
Update after questions in comments
In your example you wrote oVars(RfQ).Value
. This means "Take the document variable with the name stored in the vba variable RfQ". I'm guessing that that isn't what you want.
My guess is that the document variable is named RfQ and that you want to use that as a hardcoded name for the variable. In this case, add quotes to the document variable name, like this:
oVars("RfQ").Value = TextBox1.Value
Since you had no quotes, you introduced a new implicit vba variable, with the name RfQ, with no value. That gave the effect that you tried to read a document variable with an empty name. If you put Option Explicit
at the top of your module, you will be protected from issues like this.