Category Archives: Word

Mastering the VBA MsgBox

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.75 out of 5)
Loading...

Today shortly on how to master the Excel MsgBox. Although, the MessageBox is a common control used in most Window applications many VBA developers underestimate its usage – often making custom UserForms for tasks where the Excel MsgBox could just as well do the trick. An example? User Interaction – when user input is needed many VBA devs create custom UserForms not knowing that the MsgBox can return a Yes/No, Retry/Cancel, Ok/Cancel response when configured properly.

Example Excel MsgBox question

This example will produce a simple Excel MsgBox question with Yes/No buttons:

If MsgBox("Do you agree?", vbYesNo, "Question") = vbYes Then
    'If Yes...put some code here
Else
    'If No...do this
End If

Excel MsgBox: Creating a question
Excel MsgBox: Creating a question

Easy right? Yet this is just a sample of what you can do with the MsgBox. See the link above to learn more on how to efficiently utilize the Excel MsgBox in your VBA projects!

Common uses for the Excel MsgBox

The Excel MsgBox can be used in multiple different ways. See some valuable mentions below:

  • Notification – show the user a pop-up with an information or notification message e.g. code has finished executing
  • Error handling – show the user an error pop-up message informing that a critical error has occurred. You can add a Retry button to ask if the user wants to retry running the code
  • Question – show the user a pop-up with a simple question on how to proceed with running the code e.g. do you want to open a file?, do you want to close the workbook?

MsgBox: Messages, Notifications, Questions

The common VBA message box can be well used to interact with users to show messages (information, errors, notifications etc.) or just as well ask simple questions (Ok/Cancel, Retry/Cancel). Let us start by analyzing the parameters of the MsgBox function.

Function: MsgBox
Parameters:

  • Prompt – the message you want to show in the message box
  • Buttons – Optional. One of the following set of buttons below. You can sum them up to get different kinds of message boxes like this vbRetryCancel + vbCritical :
    • vbOKCancel – Display OK and Cancel buttons
    • vbAbortRetryIgnore – Display Abort, Retry, and Ignore buttons
    • vbYesNoCancel – Display Yes, No, and Cancel buttons
    • vbYesNo – Display Yes and No buttons
    • vbRetryCancel – Display Retry and Cancel buttons
    • vbCritical – Display Critical Message icon
    • vbQuestion – Display Warning Query icon
    • vbExclamation – Display Warning Message icon
    • vbInformation – Display Information Message icon
    • vbDefaultButton1 – First button is default
    • vbDefaultButton2 – Second button is default
    • vbDefaultButton3 – Third button is default
    • vbDefaultButton4 – Fourth button is default
    • vbApplicationModal – Application modal; the user must respond to the message box before continuing work in the current application
    • vbSystemModal – System modal; all applications are suspended until the user responds to the message box
    • vbMsgBoxHelpButton – Adds Help button to the message box
    • vbMsgBoxSetForeground – Specifies the message box window as the foreground window
    • vbMsgBoxRight – Text is right aligned
    • vbMsgBoxRtlReading – Specifies text should appear as right-to-left reading on Hebrew and Arabic systems
  • Title – Optional. The title of the Message Box
  • Help – Optional. String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided.
  • Context – Optional. Numeric expression that is the Help context number assigned to the appropriate Help topic by the Help author. If context is provided, helpfile must also be provided.

Now some examples:

Retry with Critical Error Icon

Call MsgBox("Try to run the VBA code again?", vbRetryCancel + vbCritical, "Error")
Excel VBA Tutorial: MsgBox example: Critical Error and Retry
MsgBox example: Critical Error and Retry

Align message and Question Icon

Call MsgBox("Align this to the right hand side", vbQuestion + vbMsgBoxRight, "Some Message")
Excel VBA Tutorial: MsgBox example: Information and align text
MsgBox example: Information and align text

User interaction with the MsgBox
The message box is a great tool for asking simple Yes/No questions within your VBA code. See some examples below:

If MsgBox("Do you agree?", vbYesNo, "Question") = vbYes Then
    'If Yes...put some code here
Else
    'If No...then do this
End If

This will show the following question and pause the code until the user clicks on one of the buttons:

MsgBox example: Yes/No question
MsgBox example: Yes/No question

Similarly you can create a retry question which is convenient for error handling:

  On Error Goto ErrorHandl:
Retry:
  'Some code here..
ErrorHandl:
  If MsgBox("Retry?", vbYesNo, "Question") = vbRetry Then
     Goto Retry  
  End If

Let me know what you think!

Making a VBA Automated Survey in Word

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 4.50 out of 5)
Loading...

Recently I stumbled upon an issue of creating a quick survey for clients/users. Usually you would want surveys set up in a dedicated web application like Google Forms or Survey Monkey. However, in this case I was limited to MS Word – the doc / docx survey was to be sent via email to clients/users and consolidated. Seemed like a lot of manual work. But why bother when you can use VBA? I created the survey using MS Word ContentControls (text fields, checkboxes etc.) and ActiveX objects (for option / radiobuttons only). Collecting the results was quite easy using VBA. The code is reusable for virtually any survey created this way. Below I explain my approach of making a survey in Word and how to easily consolidate the results using VBA macros (next page of this post).

Designing the survey

Most people don’t put enough effort into designing their surveys – sloppy designs, messed up document structures or simply frequent typo’s and misspelled questions. All these will heavily deteriorate the quality of your survey. Skip this section if you want just the solution/code. If you are still developing your survey, however, I encourage you to at least review the steps for designing a good survey.

Survey in Word: Well structured question survey in Word question
Example: Well structured survey question

When designing your survey always start with the following:

  • Draft your targets/objectives – what do you want to achieve with your survey? What information do you want to collect? Make a list of your objectives
  • Develop you questions and map them to your list of objectives for completeness. Remove questions that do not map to any objectives. Check if there are any duplicates – questions that provide results for the same objectives in a similar way. Are there any objectives not covered by a single question?
  • Review your list of questions – limit the survey to a reasonable amount of questions. Make sure your survey is balanced – not too many questions for a single objective
  • Decide each type of question – should they be open questions (text) and which ones should have a limited set of answers (multiple or single choice)
  • Draft answers to closed questions
  • Review all answers for completeness. Standardize questions with scales. Make sure to organize the answers and sort them appropriately
  • Make sure the survey looks clean and structured
  • Spelling and grammar – make sure there are no no typos/misspelled words etc.

Insert Word form controls

When you have completed drafting your survey and structuring it you can move on to adding the actual form controls to make you survey interactive and enable automatic results extraction.

Inserting form controls to Word
Inserting form controls to Word

Here is a list of different mapping types of question to the various controls you may use:

Type of question Form control to use Instructions
Open questions
  • Rich Text Content Control
  • Plain Text Content Control
  • Set the TAG and TITLE to be able to extract answers automatically
  • Use the Rich control only if you want the user to be able to add formatting. I would, however, advise going with the Plain control.
Open questions – Dates
  • Date Picker Content Control
  • Set the TAG and TITLE to be able to extract answers automatically
Singlechoice closed questions
  • Option Button (ActiveX Controls) / Radiobuttons
  • Combo Box Content Control / ListBox
  • Dropdown List Content Control / DropDown
  • Set the TAG and TITLE to be able to extract answers automatically
  • Use the Option Buttons when you have a small set of answers e.g. max 5. Use the Combo Box or Dropdown controls for questions will a large set of questions
  • When using Option Buttons (Radiobuttons) be sure to set the same GroupNameto all Option Buttons for all answers within a single question
Multichoice close question
  • Check Box Content Control
  • Set the TAG and TITLE to be able to extract answers automatically

Below a short example of how to correctly configure a Option Button (Radiobutton). Be sure to name the control appropriately and assign the same GroupName to all answers of a single set.

Option Button (ActiveX Control): Configuring
Option Button (ActiveX Control): Configuring

Be sure to test the survey and double-check for any typos and other editing errors twice before dispatching it to your respondents.

Automatically consolidating the results

Now that you have your survey ready it’s time for consolidating the results. If you used the form controls mentioned above you can quickly consolidate your results using the following VBA macro.

Consolidating results in Excel
Consolidating results in Excel

How to consolidate results

  • Make sure that all survey results are in a single folder and the consolidation Excel file is in a parent folder
  • Execute the ExtractResults VBA macro or click the Consolidate Survey Results in the Excel xlsm file above
  • Select the folder with the survey results
  • All results will be uploaded to the Excel file

Download example

Want an example of the above survey? Simply download the example below:

Conclusions for making a survey in Word

That’s it! Hopefully making a survey in Word will be much easier for you! I would especially like to stress on the design phase of your survey. As usually you will only get 1 hit for the survey, it is crucial to focus on you targets/objectives when drafting your questions.

Next Steps

Learn how to work with VBA in Word:
Word: Word VBA Tutorial

Word VBA Tutorial

1 Star2 Stars3 Stars4 Stars5 Stars (8 votes, average: 4.88 out of 5)
Loading...

Welcome to the Word VBA Tutorial. VBA is a great tool not only to be leveraged in MS Excel. Often it is worth to save some time doing repeatable tasks by adopting some VBA macros in Word or PowerPoint too. Today I wanted to focus a little bit on starting you off in Word VBA macro programming.

vba word tutorialWhen moving to macro programming in Word VBA you will stumble upon issues you would normally not expect in Excel. Lets take the example of moving around the Word file – in Excel you have spreadsheets which are easy to navigate around. In Word, however, you have a lot of different content e.g. text, objects like images and charts, tables etc. Navigating around Word file in VBA is the greatest challenge you will face. Today I would like to focus on that and other frequently used features in Word VBA. So let’s kick off this Word VBA Tutorial.

CONTENTS

WordVBA – navigating around Word documents, formatting etc.

word vba
Navigating / Moving
word vba
Text formatting
word vba
Tables

VBA Word Navigating

Let’s start with adding content to the most common places the start and end of a Word document in VBA. Know if you Google for this you will get tons of non-sense methods of navigating around Word files. I was truly amazed at how poorly it is documented.

Beginning and End of the Word Document

Go to the Beginning of a Word Document:

Go to the End of a Word Document:

Finding and replacing text in a Word Document with VBA

Finding and replacing text are basic functions that you will probably need to leverage every now and then.

VBA Word Text formatting

One of the first things you would want to do is probably text formatting in Word VBA.

Let’s start by adding some text to our document:

Bold & Italic

To change the font weight to bold see below:

To change the text decoration to italic see below:

Below the final result of the code above:

Word VBA Tutorial: Bold and Italic
The result: Bold and Italic

Font size and name

Using the “Hello World!” example above we can similarly change the text font name and font size as shown below:

VBA Word Tables

When editing Word files you might want to leverage tables as it is much easier to navigate around them in an automated way. My approach is to insert/modify tables in Word without and borders (invisible). This way you can guarantee a consistent and easy to navigate structure in Word. Let’s go through some of the basic functions around tables.

Add a table

Let’s add a table to the beginning of the Word document:

Edit cell text

Working on rows and columns

Formatting borders

In progress…

Get Google Maps address coordinates (latitude & longitude) in Excel VBA

1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 4.00 out of 5)
Loading...

Continuing my last post, on how to get the distance between any addresses using VBA, I wanted to add a capability to my previous Excel file that would allow me to get any address coordinates. How to quickly get the lat. and long. of an address? Again why not use Google API…

Address coordinates in Excel

This function can easily be used in any VBA algorithm like this:

In the example above the address coordinates (latitude and longitude) will be returned to lat1 and lng1 variables.

Limits and common issues

Google limits the amount of free queries you can execute. Considering the limitations and common issues please read this section of my post.