A Beginner"s Guide to Using Visual Basic for Applications

106 17
I've saved the best for last! Here's a technique that applies across the board to all of the Office applications. You'll find yourself using it a lot so we're covering it here in the Introduction.

As you start to code more sophisticated VBA programs, one of the first problems you will run into is how to find out about methods and properties of Office objects. If you're writing a VB.NET program, you'll often look for code samples and examples to solve this problem.

But when you consider all the different hosting applications and the fact that each of them have hundreds of new objects, you usually can't find something that exactly matches what you need to do.

The answer is the "Record Macro ..."

The basic idea is to turn on "Record Macro," go through the steps of a process that is similar to what you want your program to accomplish, and then check the resulting VBA program for code and ideas.

Many people make the mistake of thinking that you have to be able to record exactly the program you need. But it's not at all necessary to be that exact. It's usually good enough to record a VBA program that is just "close" to what you want and then add the code modifications to make it do the job precisely. It's so easy and useful that I will sometimes record a dozen programs with slight differences just to see what the code differences are in the result. Remember to delete all the experiments when you're finished looking at them!

As an example, I clicked Record Macro in the Word Visual Basic Editor and typed several lines of text.

Here's the result. (Line continuations have been added to make them shorter.)

Sub Macro1()'' Macro1 Macro''Selection.TypeText Text:= _"These are the times that "Selection.TypeText Text:= _"try men's souls. The "Selection.TypeText Text:= _"summer soldier"Selection.TypeText Text:= _" and the sunshine patriot "Selection.TypeText Text:= _"will, in these times, shrink from "Selection.TypeText Text:= _"the service of their country."Selection.MoveUp Unit:=wdLine, Count:=1Selection.HomeKey Unit:=wdLineSelection.MoveRight Unit:=wdCharacter, _Count:=5, Extend:=wdExtendSelection.Font.Bold = wdToggleEnd Sub
Nobody studies VBA just for itself. You always use it along with a specific Office application. So, to continue learning, there are articles here that demonstrate VBA used with both Word and Excel:

->Getting Started Using VBA: The Word Working Partner

->Getting Started Using VBA: The Excel Working Partner
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.