You have a Word document and want to run a VBA macro that uses values from the document itself. Instead of editing the macro code every time you need different input, you can pass parameters directly from the document content. This article explains three reliable methods to send data from your document to a VBA macro: using document variables, form fields, and selected text. You will learn how to set up each method and write the macro code that reads the parameters.
Key Takeaways: Passing Parameters to a VBA Macro From a Word Document
- Document variables (Variables collection): Store key-value pairs inside the document that macros can read without user interaction.
- Form fields (DropDown, TextInput, CheckBox): Let users select or type values that a macro retrieves via the
FormFieldscollection. - Selected text (Selection.Range.Text): Pass the currently highlighted text as a parameter to a macro that processes it.
Understanding How Parameters Pass From a Document to a VBA Macro
A VBA macro normally runs with fixed arguments or no arguments at all. To make the macro dynamic, you need a way to inject data from the document into the macro at runtime. Word provides several built-in objects that store data inside the document file itself or that reflect the current user selection. These objects act as the bridge between the document content and the VBA code.
The three primary mechanisms are document variables, form fields, and the Selection object. Document variables are invisible key-value pairs that travel with the document. Form fields are visible interactive controls that users fill in. The Selection object reflects whatever text the user has highlighted at the moment the macro runs. Each method has a different use case and setup procedure.
Document Variables
A document variable is a hidden string stored in the document. You set it using VBA or a quick macro, and any other macro can read it. The variable persists when you save and reopen the document. Use this method when the parameter value does not change often or when you want to set it programmatically before the main macro runs.
Form Fields
Word form fields include text boxes, drop-down lists, and check boxes. They are part of the document content and can be protected so users only fill in the fields. A macro reads the current value of any form field using the ActiveDocument.FormFields collection. This method works well when you want the user to choose or type the parameter value.
Selected Text
When the user selects text in the document, the Selection object captures that range. You can pass the selected text as a string parameter to a macro. This method is the simplest to implement because it requires no special document setup. Use it when the macro processes whatever text the user highlights.
Setting Up Each Method to Pass Parameters
Follow the steps below to implement each parameter-passing method. You must enable the Developer tab in Word first: go to File > Options > Customize Ribbon and check the Developer box.
Method 1: Using Document Variables
- Create a macro to set a document variable
Open the VBA editor with Alt+F11. Insert a new module and paste this code:Sub SetDocVar() ActiveDocument.Variables("CustomerName") = "Acme Corp" ActiveDocument.Variables("InvoiceTotal") = "1250.75" ActiveDocument.Save End SubRun this macro once to store the parameters in the document.
- Create the main macro that reads the variables
Add this code to the same module:Sub ProcessInvoice() Dim custName As String Dim invTotal As String custName = ActiveDocument.Variables("CustomerName").Value invTotal = ActiveDocument.Variables("InvoiceTotal").Value MsgBox "Customer: " & custName & vbCrLf & "Total: " & invTotal End SubRun ProcessInvoice to see the parameters displayed.
- Update the variable value
To change the parameter, edit the SetDocVar macro with the new value and run it again. The updated value is available to any macro that reads the variable.
Method 2: Using Form Fields
- Insert a text form field in the document
On the Developer tab, click the Legacy Tools button (the toolbox icon). Under Legacy Forms, click the Text Form Field button. A shaded text box appears. Right-click it and choose Properties. In the Bookmark box, typetxtCustomer. Set the Type to Regular Text. Click OK. - Insert a drop-down form field
Click Legacy Tools again and select Drop-Down Form Field. Right-click the field and choose Properties. Set the Bookmark toddlRegion. Click Add to enter items like North, South, East, West. Click OK. - Create the macro that reads the form fields
Open the VBA editor and add this code:Sub ProcessFormData() Dim customer As String Dim region As String customer = ActiveDocument.FormFields("txtCustomer").Result region = ActiveDocument.FormFields("ddlRegion").Result MsgBox "Customer: " & customer & vbCrLf & "Region: " & region End SubRun the macro after filling in the form fields.
- Protect the document for form filling (optional)
On the Developer tab, click Restrict Editing. Under Editing restrictions, check Allow only this type of editing in the document and choose Filling in forms. Click Yes, Start Enforcing Protection. Users can only interact with the form fields.
Method 3: Using Selected Text
- Select text in the document
Highlight any word or phrase in the document body. - Create the macro that captures the selection
In the VBA editor, add this code:Sub ProcessSelection() Dim selectedText As String selectedText = Selection.Range.Text ' Remove the trailing paragraph mark if present If Right(selectedText, 1) = vbCr Then selectedText = Left(selectedText, Len(selectedText) - 1) End If MsgBox "You selected: " & selectedText End Sub - Assign the macro to a keyboard shortcut or button
Go to File > Options > Customize Ribbon. Click Customize next to Keyboard Shortcuts. Under Categories, select Macros. Under Macros, select ProcessSelection. Press a shortcut like Alt+Shift+S and click Assign. Now you can select text and press the shortcut to run the macro.
Common Pitfalls When Passing Parameters From a Document
Document Variable Returns an Empty String
If the variable has never been set, reading it returns an empty string. Always run the macro that sets the variable before the macro that reads it. To avoid errors, check if the variable exists with On Error Resume Next or iterate the Variables collection.
Form Field Result Contains Extra Spaces or Line Breaks
The Result property returns the exact text the user typed. Trim leading and trailing spaces with the Trim function in your macro. If the field contains a line break, replace it with a space using Replace.
Selection Includes Non-Printing Characters
When the user selects text that includes the end-of-cell marker in a table or the end-of-paragraph mark, the Selection.Range.Text property includes those characters. Use the code shown in Method 3 to strip the trailing paragraph mark. For table cells, check if Selection.Information(wdWithinTable) is True and handle accordingly.
Document Variables vs Form Fields vs Selected Text: Comparison
| Item | Document Variables | Form Fields | Selected Text |
|---|---|---|---|
| Setup effort | Low (VBA macro only) | Medium (insert fields, set properties) | Low (no setup needed) |
| User interaction | None (hidden) | Required (user fills in) | Required (user selects text) |
| Parameter persistence | Yes (saved with document) | Yes (saved with document) | No (lost after selection changes) |
| Best for | Fixed or programmatically set parameters | User-driven input with controlled options | Quick one-time processing of highlighted content |
You can now pass parameters from your Word document to a VBA macro using document variables, form fields, or selected text. Choose the method that fits your workflow. For a next step, explore how to pass parameters to a macro from a Word table cell by combining the Selection.Information(wdStartOfRangeColumnNumber) property with the Cells collection. An advanced tip: use document variables to store the last-used parameter values so the macro remembers them between runs.