Creating Excel Macros in Visual Basic

Introduction:

Excel is a popular spreadsheet application from Microsoft. It is all the more powerful for its ability to automate tasks. Tasks, both routine and complex, can be automated into a macro. Macros are essentially shortcuts that trigger an action or sequence of actions. Macros are written in the Visual Basic language. Visual Basic comes bundled with Microsoft Excel.

Macros can be created in two ways.

  1. You can write the macro in visual basic, or
  2. You can record the macro, and then edit the macro.

Creating a Macro: A Simple Hello World macro

Derived from an excellent tutorial by Gary Radley (Select Introduction). In Microsoft Excel:
  1. Open a new document
  2. Open the Control Toolbox Toolbar
    View->Toolbars->Control Toolbar
  3. Add a command button
  4. Double click on the new command button
    This will open the Visual Basic Editor
  5. Between the lines:
       Private Sub CommandButton1_Click()
    
       End Sub
       
    Add:
        MsgBox ("Hello World")
       
  6. File->Close and Return to Microsoft Excel
  7. Exit Design Mode (upper left hand button in Control Toolbox Toolbar)
  8. Click on your button
  9. Voila!

Recording a macro:

Derived from the excellent
tutorial by James Crowley
  1. Open a new document
  2. Click Tools->Macro->Record New Macro
  3. Enter a name and description for the macro
    The Macro will record until you press the Stop button
  4. Create title headings in the following columns:
    • A1: FirstName
    • B1: LastName
    • C1: Exam1Grade
    • D1: Exam2Grade
    • E1: FinalGrade
    Bold the column headings, and make the background blue
  5. Stop recording the Macro
  6. View and edit the Macro
    Tools->Macro->Visual Basic Editor
  7. When the editor is open, you should see the code for the macro you just created.
    If you don't:
    • click on Tools->Macros
    • Select the name of the macro you've just created and click Edit
  8. To see the macro in action
    • go to Sheet2 (or add a new sheet)
    • Select Tools->Macros...
    • Select the name of the macro you've just created and click Run

Visual Basic Basics:

Visual Basic is a Microsoft programming Language. VB is an event-driven programming language. This means the VB application performs an action based on an user-supplied event, eg. a mouse click or a key press.

When writing a VB application, you need to create a component. The component is usually an object such as a button or a check box. The component is associated with properties and code.

Let's take a closer look at the macro we have created in the previous exercise.

   1   Sub CreateHeaders()
   2     Range("A1").Select
   3     ActiveCell.FormulaR1C1 = "First Name"
   4     Range("B1").Select
   5     ActiveCell.FormulaR1C1 = "Last Name"
   6     Range("C1").Select
   7     ActiveCell.FormulaR1C1 = "Exam 1 Grade"
   8     Range("D1").Select
   9     ActiveCell.FormulaR1C1 = "Exam 2 Grade"
  10     Range("E1").Select
  11     ActiveCell.FormulaR1C1 = "Final Grade"
  12     Range("A1:E1").Select
  13     Selection.Font.Bold = True
  14     With Select.Interior
  15       .ColorIndex = 33
  16       .Pattern = xlSolid
  17     End With
  18   End Sub

Each macro is stored as a subroutine. This subroutine is "CreateHeaders" is displayed in line 1. Lines 2-11 show header creation. In line 3, we see that command to select a range of cells. In this case, the selection is a single cell. Line 4 updates the formula value of the selected cell (ActiveCell).

Line 12 is an example of selecting multiple cells. The following lines show the actions being applied to this range of cells. In line 13, it indicates that the selection should be changed to a bold font. Lines 14-17 show a With structure. The With structure appends the properties in line 15 and 16 to the statement specified in line 14. Lines 14-16 could also be written as:

  Select.Interior.ColorIndex = 33
  Select.Interior.Pattern = xlSolid

In VB, all subroutines and control loops, except for For/ForEach loops, must be closed. This can be done with a simple end statement, as shown in lines 17 and 18.

Control:

VB provides several ways to control programming logic. This allows programs to return output that varies on input.

Variables:

In VB or any programming language, you will sometimes find that you need to store a value temporarily. In VB, you declare variables, with the "Dim" statement. You can set the variable to have a certain property.

  Dim newRow As Integer
  Dim dirFile As String
  

Functions:

Functions are quite useful. Instead of assigning a static value to a variable, you can create a function that will generate a value based on the condition that you give it. VB and Excel have quite a few built-in functions. eg. Rnd (VB) or RAND (Excel). It is quite easy to create your own custom function in VB, with the Function stanza. In this new version of Division, we will swap the Divisor w/ the Dividend.

    Function newDivision()
      Quotient = Dividend/ Divisor
    End Function
    

Helpful Links

Visual Basic Download:

If you don't have Visual Basic bundled w/ Excel, you can get VB from Microsoft's site.

Books:

Complex Macros

Macros can be more complex than those shown above. To perform a complex task, divide the task into several simple macros. Then create a parent macro that runs all the smaller macros.

A Practical Application: Simple Interest Calculator

Let's create a macro to calculate simple interest every time you click the button.