Differences
This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision | |||
|
applications:visual-basic-for-applications:vba-for-excel [Apr 3, 2026 12:27 PM] 101.47.45.145 removed |
— (current) | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | = VBA and Macros for Excel 2007 = | ||
| - | This is a quick overview/ | ||
| - | == Basic Setup == | ||
| - | |||
| - | * Install Excel 2007 and enable the Developer Toolbar (Office Menu -> Excel Options). | ||
| - | * Make sure you can get into the VBA Editor via the Developer Toolbar. Once there, you may want to set the ' | ||
| - | * Note that there is only one VBA editor for //ALL// workbooks that you have open. | ||
| - | * The VBA Editor has a few key windows: | ||
| - | - **Project**: | ||
| - | - **Properties**: | ||
| - | - **Editor**: The main editor, where you write code | ||
| - | - **Object Browser**: Press F2 to get the Object Browser, which lets you see a comprehensive view of all Excel classes | ||
| - | - **Debugging Windows**: There are several windows that you use for debugging, such as the Watches window which lets you watch variables. See [[vba-for-excel# | ||
| - | |||
| - | == VBA Language Constructs == | ||
| - | |||
| - | === VBA: An Object-Oriented Language === | ||
| - | * VBA is object oriented. So we have an object like a ' | ||
| - | * As with every other object oriented language, an object can have both properties and methods (functions). However, the syntax for calling functions is a little weird:< | ||
| - | Object.myProperty = 3 ' Assign the value 3 to the property ' | ||
| - | Object.myFunction(3, | ||
| - | Object.myFunction setting := 3 ' Call ' | ||
| - | </ | ||
| - | * You'll note there are two different types of function calls. The first is the one that is probably familiar to you; you pass a list of arguments in a specific order, as defined by the function that you're calling. The second allows you to specific which arguments get which values; in the example above, '' | ||
| - | * Also as with any other object-oriented language, objects can have properties that are, in fact, other objects. Similarly, you can pass objects as arguments to functions. | ||
| - | * Example: If you look at the code < | ||
| - | * You'll note that we passed '' | ||
| - | |||
| - | === Variables === | ||
| - | * Variables in VBA can either be statically or dynamically typed, but most developers prefer static typing (see below). | ||
| - | * Variables are declared with '' | ||
| - | Dim myVariable As Range | ||
| - | </ | ||
| - | * Then they can be set with <code vba> | ||
| - | myVariable = 2 | ||
| - | Set myVariable = Range(" | ||
| - | </ | ||
| - | * Dynamic typing is done via the '' | ||
| - | |||
| - | === Functions and Subroutines === | ||
| - | * VBA supports both functions and subroutines. The difference is that functions can return a value, and sub-routines can't. | ||
| - | * Subroutine declaration:< | ||
| - | Sub mySubroutine(firstName As String, lastName As String) | ||
| - | ' | ||
| - | End Sub | ||
| - | </ | ||
| - | * Function declaration:< | ||
| - | Function myNameFunction(firstName As String, lastName As String) As String | ||
| - | ' | ||
| - | ' | ||
| - | | ||
| - | End Function | ||
| - | </ | ||
| - | * Functions can be called from a cell, and populate that cell with a value. For example, you could call:< | ||
| - | =myNameFunction(A1, | ||
| - | </ | ||
| - | |||
| - | === Loops === | ||
| - | * Surprise, surprise. VBA supports the all loops that you'd expect. | ||
| - | * '' | ||
| - | For i = 1 To 10 | ||
| - | ' do something with i | ||
| - | Next i | ||
| - | </ | ||
| - | * You can also make these a bit more complex, for example running backwards and incrementing by more than just one: <code vba> | ||
| - | For i = 300 To 200 Step 10 | ||
| - | ' i will go from 300 to 200, in increments of 10 | ||
| - | Next i | ||
| - | </ | ||
| - | * '' | ||
| - | Dim testVar As Boolean | ||
| - | testVar = true | ||
| - | Do While testVar | ||
| - | ' do something, and eventually set testVar = false, which breaks out of the loop | ||
| - | Loop | ||
| - | </ | ||
| - | * '' | ||
| - | For Each cell in myRange | ||
| - | ' do something with each cell | ||
| - | Next cell | ||
| - | </ | ||
| - | === Flow Control === | ||
| - | * Standard flow control structures are also supported. | ||
| - | * '' | ||
| - | If X > 0 Or Y > 0 Then | ||
| - | ' do something | ||
| - | Else | ||
| - | ' do something else | ||
| - | End If | ||
| - | </ | ||
| - | * '' | ||
| - | Select Case action | ||
| - | Case ' | ||
| - | ' do load proceedure | ||
| - | Case ' | ||
| - | ' do save proceedure | ||
| - | Case Else | ||
| - | ' print an error; nothing matched | ||
| - | End Select | ||
| - | </ | ||
| - | |||
| - | === Arrays === | ||
| - | * VBA supports both single and multi-dimensional arrays. | ||
| - | * VBA is a little weird; if you declare an array like this: '' | ||
| - | * Examples: <code vba> | ||
| - | Dim myArray(2) | ||
| - | Dim myArray(2, | ||
| - | </ | ||
| - | |||
| - | === Collections === | ||
| - | * A ' | ||
| - | Dim myCollection As New Collection | ||
| - | | ||
| - | | ||
| - | | ||
| - | | ||
| - | </ | ||
| - | |||
| - | === Regular Expressions === | ||
| - | |||
| - | * VBA supports regular expressions via an add-in. To enable it, go to the Visual Basic Editor and select 'Tools -> References' | ||
| - | * Here's an example of a regular expression:< | ||
| - | Dim regex As New RegExp | ||
| - | |||
| - | ' Set regex properties; we're looking for a string that starts with ' | ||
| - | With regex | ||
| - | .MultiLine = False | ||
| - | .Global = True | ||
| - | .IgnoreCase = False | ||
| - | .Pattern = " | ||
| - | End With | ||
| - | |||
| - | regex.Test(" | ||
| - | regex.Test(" | ||
| - | </ | ||
| - | |||
| - | == Excel Specific VBA == | ||
| - | |||
| - | === Ranges === | ||
| - | * The range object is probably the thing you'll interact with most in Excel, because it lets you select and act on bits of data. | ||
| - | * A Range may be a single cell, or a group of cells. Most common syntax for a range:< | ||
| - | Range(" | ||
| - | Range(" | ||
| - | Range(" | ||
| - | Range(" | ||
| - | Range(" | ||
| - | Worksheets(" | ||
| - | </ | ||
| - | * You can also access a named range, e.g. '' | ||
| - | * You can get a specific item in a range by using '' | ||
| - | * '' | ||
| - | * '' | ||
| - | |||
| - | === Cells === | ||
| - | * The '' | ||
| - | * '' | ||
| - | |||
| - | === Names === | ||
| - | * Names are a little bit like persistent variables for Excel. You can store data in them when you need it to persist across sessions, but you don't want to store it in a hidden part of your worksheet. | ||
| - | * Basically, a ' | ||
| - | * Names can either be local (specific to a single worksheet) or global (common across all worksheets). | ||
| - | * You create names like this:< | ||
| - | ActiveWorkbook.Names.Add Name: | ||
| - | ActiveSheet.Names.Add Name: | ||
| - | </ | ||
| - | * You access names via the names object. For example, to delete a name:< | ||
| - | Names(" | ||
| - | </ | ||
| - | |||
| - | === Worksheet Functions === | ||
| - | * VBA has quite a few built in functions, but there are quite a few more built into Excel and not VBA. You need to access these via the '' | ||
| - | * Reportedly, switching between VBA and Excel causes significant overhead, so it should be avoided if possible. | ||
| - | |||
| - | === R1C1 Style Formulas === | ||
| - | * In addition to standard A1 style formulas, Excel supports R1C1 style formula entry. Every cell is assigned a numeric row and column index, so cell R2C2 would be B2 (second row, second column). | ||
| - | * R1C1 style formulas can make your code more elegant in many cases | ||
| - | * R1C1 syntax supports both absolute references: R5C3 as well as relative references: R[5]C[3]. The former would go to the fifth row, third column. The latter would go down five rows and over three columns //from the current cell// | ||
| - | * You can also do a mixed reference: R4C[-1] would go to the fourth row, back one column from the current cell. | ||
| - | === Charts === | ||
| - | * Create a Chart using the Shapes object; e.g.:< | ||
| - | ActiveSheet.Shapes.AddChart.Select | ||
| - | ActiveChart.SetDataSource Source: | ||
| - | ActiveChart.ChartType = xlColumnClustered | ||
| - | </ | ||
| - | * If you need to move a chart, you need to move the parent '' | ||
| - | ActiveChart.Parent.Left = Range(" | ||
| - | ActiveChart.Parent.Top = Range(" | ||
| - | </ | ||
| - | * Some arguments, such as type and size, can also be passed to AddChart, see the Excel docs for details. | ||
| - | === Events === | ||
| - | |||
| - | * Like many other languages, VBA uses an event driven model for running code when certain things happen to a workbook | ||
| - | * There are four types of events: | ||
| - | * **Application Events** - Events at the application level, such as '' | ||
| - | * **Workbook Events** - Events at the workbook level, such as '' | ||
| - | * **Worksheet Events** - Events at the worksheet level, such as '' | ||
| - | * **Chart Events** - Events specific to a chart, such as '' | ||
| - | * Code for events is stored in the appropriate Excel module. For example, Workbook events are stored in the '' | ||
| - | * To add a subroutine to handle an event, use the Object drop-down and Procedure drop-down from the top of the code window. | ||
| - | |||
| - | |||
| - | == Misc == | ||
| - | |||
| - | === Error Handling === | ||
| - | * Many functions in Excel return an error if something goes wrong, which stops the execution of the program. | ||
| - | * If you'd rather have execution continue, and handle the error, you can catch errors like this:< | ||
| - | On Error Resume Next | ||
| - | Names(" | ||
| - | Range(" | ||
| - | </ | ||
| - | |||
| - | === Debugging === | ||
| - | |||
| - | * VBA sports all the usual suspects for debugging: Step Into, Step Over, Run to Cursor, adding breakpoints, | ||
| - | * All of the debugging functionality is accessed from the Debug menu of the Visual Basic for Applications IDE. | ||