How to Write Excel Macros in VBA
Microsoft Excel is a spreadsheet application which is a component of Microsoft Office. Excel was originally developed for the Macintosh personal computer in 1985. The first Windows version of Excel was released in 1987 and by 1988 it was outselling the leading spreadsheet application, Lotus 1-2-3. In 1999 Excel was released as a component of Microsoft Office 2000. Microsoft has included Visual Basic for Applications (VBA) in order to provide a way to automate time-consuming tasks as well as to create custom forms for Excel as well as other Office applications. One of the features of VBA is the ability to easily create a macro using code.
Instructions
-
-
1
Open Excel.
-
2
Open VBA by holding the "Alt" key and pressing "F11."
-
-
3
Click "Insert" on the menu to activate the Insert options.
-
4
Click on "Module" to create a new module.
-
5
Type "Sub Count()" on the module form to create a subroutine called "Count." The "End Sub" code is automatically added by VBA.
-
6
Type the following code between "Sub Count()" and "End Sub" so that the subroutine looks like the following:
Sub Count()
rowCount = Selection.Rows.Count
MsgBox rowCount
End Sub -
7
Close the VBA window. There is now a Macro named Count available on this Excel Book.
-
8
Select any number of rows in the worksheet by left-clicking the sheet and dragging the mouse to highlight the desired rows and columns.
-
9
Click "Developer" on the Excel menu.
-
10
Click the "Macros" button to open the Macro dialog box. The new Macro, created in Step 6, will be listed in the Macro Names box.
-
11
Click on the "Count" macro.
-
12
Click "Run" to run the macro. A window will open displaying the number of rows in your selection.
-
13
Save the Excel Workbook.
-
1
Tips & Warnings
This is just a simple example of how to write a Macro using VBA; there are many uses for Macros, any of which can be written in VBA rather than recording the Macro step by step.