VBA – MS Word tricks with VBA

VBA is a Microsoft script language, mostly used with Excel. And there are reasons for this – mainly, the skills needed to use VBA are easily grasp by those, using Excel on a daily basis. The second reason is that only in Excel the VB Editor gives a possibility to record a macro. Thus, if you want to use VBA in Access, Word, Outlook or any other MS Application, you should know the commands from before and you need some skills, as far as you cannot just record the macro and simply edit it later.

That is why I have decided to give some useful examples for VBA with Word. This is really not popular, because Word is used mainly for writing 🙂 and not for creating business models, but some of the examples may be useful.

The first example of VBA will simply change the font of the Word document to “Times New Roman”. In order to make it fancier, we will ask a question before the change:


The code is pretty much straightforward, we get a message box, the result of the message box is assigned to a variable “intResult”, and if this result is “6”, we change the font. In VBA, “6” is the value, generated from the “Yes” button:



So, the code looks like this:

Pretty much, the code may seem a little useless, because the same result can be achieved if you simply select the whole text in Word and change the font. No VBA, nothing. Anyway, this is a good code for reference, if you need to select all text in Word (and Word does not have macro recorder).

In the second example, we will add automatically some text at the beginning and the end of the document. The text added will be hard coded, for easier understanding of the example. Pretty much, the logic is as in the previous example, we simply ask with a message box and if the answer is VbYes, we add some text at the beginning and at the end:

Finally, the last example is something useful – it changes all font with some size to another size. Thus, imagine that you are writing a master thesis of 60 pages, and suddenly you decided to change the size of font from 9 to 10. You cannot go and select all, because there are other fonts. Thus, you need to use a macro! 🙂 :

The macro here makes a search in the text for font with size 9 and sets it to size 10. The trick is in the usage of a loop in a “With… End With” structure. The trick of the finding is in the clearing of the format.

Pretty much, that is all. If you want to test the macros, you may download the files from here.

Tagged with: , , , ,