View Single Post
 
Old 09-22-2024, 09:58 AM
Trey@Shaffer-Family.com Trey@Shaffer-Family.com is offline Windows 10 Office 2016
Novice
 
Join Date: Sep 2024
Posts: 1
Trey@Shaffer-Family.com is on a distinguished road
Default vba-MSWord, Execute string as command

At a high level, I am building a format command, within VBA, like,
"ActiveDocument.Words(intWordPointerL).Font.It alic = True"

I then want to execute the command.

At first it seemed like "Eval" or "Application.Run" might be a solution, but I haven't gotten them to work.
Seems like they are looking for existing function/sub references, rather than a free form string.
I'd like something like the PowerShell Invoke-Expression command.

To simplify, I'm working with the base command, preformed,
"ActiveDocument.Words(intWordPointerL).Font."
Then appending one of a variety of qualifiers, like "Italic = True".


Tried using "Eval".
Tried using Application.Run.
Both seem to require a reference to and existing Macro.

If I can't invoke the command directly, can I create a macro on the fly and then invoke it?

I found this answer to a similar question relative to Excel,
VBA - Execute string as command in Excel - Stack Overflow

If it works in Excel, it could probably be adapted to work in Word.
I'm not strong in VBA.
I don't understand how to convert this Excel-centric code for MS-Word usage.

================================================== ===========================
Sub test()
Set VBComp = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_S tdModule)
VBComp.Name = "NewModule"
Set VBCodeMod = ThisWorkbook.VBProject.VBComponents("NewModule").C odeModule
Dim l_counter As Long
l_counter = 1
With VBCodeMod
LineNum = .CountOfLines + 1
.InsertLines LineNum, _
"Sub MyNewProcedure()" & Chr(13) & "UserForm1.chb_g_ba" & l_counter & ".Visible = True" & Chr(13) & "End Sub"
End With
'run the new module
Application.Run "MyNewProcedure"
UserForm1.Show
'Delete the created module
ThisWorkbook.VBProject.VBComponents.Remove VBComp
End Sub
Reply With Quote