~7m skim, 1,372 words, updated Feb 7, 2025
Enterprise grade spreadsheeting.
Man has always had the spreadsheet for working purposes. If you peer backwards into history, you will find cruneiform tablets with spreadsheets on them. Tables are an endlessly useful and logical way to organize the material world. In the new industrial era, Microsoft Excel has become the humble program to take this crown, being the preferred format for companies of all sizes to practically and effectively complete their work.
Martin Shkreli has a Finance Lessons playlist1 with a focus on Excel.
Like all Microsoft Office products, Excel can be automated with VBA, Visual Basic for Applications, which is the primary topic of this manual. Visual Basic was first released in 1991 as an easy way (akin to BASIC) to work with Microsoft products and develop Windows applications.2
Honestly, I never expected to dig into this stuff. I assumed my knowledge of VB/VBA would never extend past this meme, but here we are -
“I’ll create a GUI interface in Visual Basic, see if I can track an IP address.” – CSI Scene/Meme
Documentation
Cheat Sheets
Generally - across programming - macros (from the Ancient Greek “makros” meaning long) are meant to simplify a longer activity. In Excel, they are more akin to the concept of automation scripting - the UI is puppeteered with functions and code to complete a repetitive or difficult task.
Examples:
Before starting, let’s set up Excel for some hacking.
Developer
option to include it in the ribbon.Generally in this section we will cover the following:
In your sample document (whatever you want) click Developer > Record Macro
, don’t bother setting a shortcut, and perform a few actions.
Then hit Developer > Stop Recording
. You can view the code for this
macro by (assuming this is a fresh project) hitting Alt-F11
and
looking in Module1
for the generated code.
Sub Macro1()
'
' Macro1 Macro
' Set Column Types
'
' Set the column to date format
Columns("A:A").Select
Selection.NumberFormat = "m/d/yyyy"
Columns("A:A").EntireColumn.AutoFit
' Set the top item in the column
Range("A1").Select
Selection.NumberFormat = "General"
Selection.Font.Bold = True
End Sub
Aside: Save your macros in your Emacs configs with M-x insert-kbd-macro
To reassign the macro to another keybinding in the future, you can hit
Developer > Macros
and in the Options
for your macro edit the shortcut
and description.
Form buttons can be added to sheets with Developer > Insert > Button (Form Control)
- clicking the button will then run the macro.
The entire Excel/VBA interop system can be accessed and manipulated
from the VBA editor, which can be opened with Alt + F11
. On the left, in
the Project pane, you will see an object for each sheet in your
workbook along with one for the entire workbook.
Useful Commands (M - Meta/Alt, C - Control, S - Shift)
Keyboard Shortcut | Action |
---|---|
M-F11 | Open the VBA Editor |
C-g | Open the immediate window (a repl for procedures) |
C-j | When hovering over an object, list its properties |
C-<SPACE> | Autocomplete |
F2 | Object browser |
F4 | Properties window |
F5 | Run the current procedure or macro |
F8 | Debug mode |
C-<BREAK> | Halt a running macro |
S-F2 | Jump to definition for a function or variable |
C-f | Find dialog |
C-h | Find and replace |
The VBA Editor enables you to edit a tree of VBA files corresponding to:
Within Workbook and Sheet files, you can add event-triggered functions that are tied to the entire file or a specific sheet.
Workbook_Open
triggers when the file is openedWorkbook_BeforeClose
triggers before closingWorkbook_SheetChange
detects cell editsWorksheet_Change
within a sheet’s file runs after an editWorksheet_SelectionChange
triggers when a cell is selectedAll macros and automation logic should be stored in Modules. Use your head and split code between modules in a sensible manner.
Private Sub Workbook_Open()
MsgBox "Welcome! This workbook opened successfully.", vbInformation, "Hello!"
End Sub
Dim var1 As Integer
var1 = 2
userInput = InputBox("Test")
Debug.Print "User input was: " & userInput & " and var1 is " & var1
VBA has the same data types as any programming language. See this cheat sheet page for a good set of examples. Notably:
Variant
type can take anything (and is the default type)True
and False
M/D/YYYY
- very AmericanRange("A1:A4")
Worksheet("Boiler 1")
Workbooks(1)
All variables are created in a given scipe. When they lose scope, the value is garbage-collected. You can use the following to declare variables:
Procedures are contained within:
…both of which can be called in a similar manner.
' Sub procedure definition with two arguments:
Sub SubComputeArea(Length, TheWidth)
Dim Area As Double ' Declare local variable.
If Length = 0 Or TheWidth = 0 Then
' If either argument = 0.
Exit Sub ' Exit Sub immediately.
End If
Area = Length * TheWidth ' Calculate area of rectangle.
Debug.Print Area ' Print Area to Debug window.
End Sub
This example is from the VBA Docs :
Function Bonus(performance, salary)
If performance = 1 Then
Bonus = salary * 0.1
ElseIf performance = 2 Then
Bonus = salary * 0.09
ElseIf performance = 3 Then
Bonus = salary * 0.07
Else
Bonus = 0
End If
End Function
' In a subroutine:
Debug.Print Bonus(1, 2390) '-> 239
Here is a very simple example of a macro that shows a pop-up input box to the user, and after hitting OK, presents the same data to the user.
Sub Macro4()
Dim response As String
response = InputBox("Write anything.")
MsgBox ("Your input: " & response)
End Sub
Function FindColumnByName(sheet As Worksheet, columnName As String) As Integer
Dim rng As Range
Dim lastCol As Integer
' Find the last column in the first row
lastCol = sheet.Cells(1, sheet.Columns.Count).End(xlToLeft).Column
' Loop through the first row to find the column name
For Each rng In sheet.Range(sheet.Cells(1, 1), sheet.Cells(1, lastCol))
If Trim(LCase(rng.Value)) = Trim(LCase(columnName)) Then
FindColumnByName = rng.Column
Exit Function
End If
Next rng
' Return 0 if column not found
FindColumnByName = 0
End Function
Sub TestFindColumn()
Debug.Print FindColumnByName(Sheet1, "Paystop") '-> 3
End Sub
Power Automate is a shiny new toy from Microsoft that enables the easy creation of macro-style event-driven workflows in the cloud. While not as powerful as macros, there are a certain number of useful tasks that can be performed with power automate.
From Hacker News - “So there’s this weird playlist about Excel by Martin Shkreli of all people…” ↩︎
“Writing a Sub procedure” microsoft.com ↩︎
Pages are organized by last modified.
Title: Excel & VBA
Word Count: 1372 words
Reading Time: 7 minutes
Permalink:
→
https://manuals.ryanfleck.ca/excel/