VBA course · Lesson 32 of 33
VBA best practices: clean code, sharing and security
Write VBA others can trust: naming, Option Explicit, modules, constants, code names, version control, digital signatures, add-ins and safe handling of secrets.
Writing a macro that works is the first half of the job. The second half is writing one that still works next year, that a colleague can understand, and that people can open without lowering their security. This lesson collects the habits that separate a quick hack from a tool a team can rely on: naming, structure, constants, protecting against sheet renames, keeping versions, signing your code and sharing it safely.
None of these rules are enforced by Excel. They are agreements with your future self and your colleagues, and they cost very little once they become habits.
Option Explicit, always
Option Explicit at the top of a module forces you to declare every variable with Dim. Without it, a typo such as totl = totl + amount silently creates a new, empty variable and your total is wrong with no error. With it, the code refuses to compile and highlights the typo (Variables and data types: Dim, Option Explicit and scope).
Make it automatic: in the VBA editor choose Tools > Options > Editor and tick Require Variable Declaration. From then on every new module starts with Option Explicit. Existing modules are not changed, so add the line to them by hand. On the Mac the setting is under Tools > Options in the VBA editor too.
Then use Debug > Compile VBAProject regularly. It checks the whole project for undeclared variables, missing End Ifs and type mismatches before a user finds them at run time.
Naming things
Good names make comments almost unnecessary. Compare x = c(i, 3) * 1.2 with grossAmount = netAmount * (1 + VAT_RATE). Some widely used conventions:
| What | Convention | Examples |
|---|---|---|
| Procedures | Verb + noun, PascalCase | CreateInvoices, ExportReportToPdf |
| Functions | What they return | GetLastRow, IsValidEmail, NetToGross |
| Variables | camelCase, meaningful | lastRow, customerName, invoiceTotal |
| Booleans | is / has / can prefix | isOverdue, hasHeader |
| Constants | UPPER_CASE with underscores | VAT_RATE, MAX_ROWS |
| Module-level variables | m prefix | mCalcMode, mLog |
| Modules | mod prefix | modInvoices, modSpeed, modUtils |
| Classes and forms | cls / frm prefix | clsInvoice, frmNewCustomer |
Some developers also use type prefixes such as strName or lngRow (Hungarian notation). It is not wrong, just less common in modern code; whatever you choose, be consistent within a project. Avoid names that clash with VBA or Excel keywords, such as Date, Name, Value or Range, as variable names: the code may run, but it becomes confusing and can hide built-in functions.
Organising modules
A workbook with one module called Module1 containing 2,000 lines is hard to work with. Split code by purpose:
modMain: the entry points users run from buttons, short and readable.- One module per feature:
modInvoices,modImport,modEmail. modUtils: small reusable helpers such asGetLastRow,PickFolder,SheetExists.modSpeedormodSettings: shared settings and constants.- Class modules and forms for objects and dialogs (Class modules: build your own objects in VBA, UserForms: build a data-entry form in VBA).
Keep each procedure short, ideally fitting on one screen, and doing one thing. A long macro becomes readable when its main procedure reads like a table of contents:
Option Explicit
Public Sub RunMonthlyClose()
If Not ConfirmRun("Run the monthly close for " & Format(Date, "mmmm yyyy") & "?") Then Exit Sub
ImportBankTransactions
MatchPaymentsToInvoices
BuildAgedDebtorsReport
ExportReportsToPdf
MsgBox "Monthly close finished.", vbInformation
End Sub
Private Function ConfirmRun(ByVal question As String) As Boolean
ConfirmRun = (MsgBox(question, vbYesNo + vbQuestion, "Please confirm") = vbYes)
End Function
' Placeholders so the module compiles; in a real project each one
' lives in its own feature module (modImport, modReports, ...)
Private Sub ImportBankTransactions()
Debug.Print "Importing bank transactions..."
End Sub
Private Sub MatchPaymentsToInvoices()
Debug.Print "Matching payments..."
End Sub
Private Sub BuildAgedDebtorsReport()
Debug.Print "Building aged debtors report..."
End Sub
Private Sub ExportReportsToPdf()
Debug.Print "Exporting PDFs..."
End SubThe four steps are placeholders here; in a real project each would be a Public procedure in its own module. Mark procedures Private when only their own module needs them. Private procedures do not appear in the Macros dialog (Alt+F8), so users only see the real entry points.
Comments that help
Comments should explain why, not repeat what the code already says.
Option Explicit
Sub CommentExamples()
Dim r As Long
' Bad: repeats the code
r = 2 ' set r to 2
' Good: explains a decision a reader could not guess
' Row 1 holds the export's title and row 2 the headers since the
' new ERP version (March 2026), so data starts in row 3.
r = 3
Debug.Print r
End SubAt the top of each module, a short header saying what the module is for, who maintains it and what it depends on ("needs a sheet called Customers with headers in row 1") saves the next person an afternoon. Delete commented-out blocks of old code once a change is tested; version control (below) remembers the old version for you.
Constants instead of magic numbers
A magic number is a bare value in the code whose meaning is unclear and which may appear in several places: * 1.2, Cells(r, 7), "C:\Reports\". Give them names in one place:
Option Explicit
' VAT and layout settings: change them here, not in the code below
Private Const VAT_RATE As Double = 0.2
Private Const FIRST_DATA_ROW As Long = 2
Private Const COL_CUSTOMER As Long = 2
Private Const COL_NET As Long = 5
Private Const COL_GROSS As Long = 6
Sub FillGrossAmounts()
Dim ws As Worksheet
Dim r As Long
Set ws = ThisWorkbook.Worksheets("Orders")
For r = FIRST_DATA_ROW To ws.Cells(ws.Rows.Count, COL_CUSTOMER).End(xlUp).Row
ws.Cells(r, COL_GROSS).Value = Round(ws.Cells(r, COL_NET).Value * (1 + VAT_RATE), 2)
Next r
End SubWhen the VAT rate changes or someone inserts a column, you edit one line. Values that business users should change themselves (rates, folder paths, email addresses) are often better kept on a Settings sheet with named ranges, so nobody has to open the editor.
Protect yourself against renamed sheets
Worksheets("Data") breaks the moment a user renames the tab to "Data 2026". Every sheet also has a code name, set in the Properties window (F4) under (Name). In the Project Explorer it appears first, followed by the tab name in brackets: Sheet1 (Data). Users cannot change it from Excel. Give your important sheets meaningful code names such as shData, shSettings, shInvoice, and refer to them directly:
Option Explicit
Sub UseCodeNames()
' shSettings is the code name set in the Properties window
Dim vat As Double
vat = shSettings.Range("B2").Value
shData.Range("A1").Value = "Updated " & Format(Now, "yyyy-mm-dd hh:mm")
Debug.Print "VAT rate: "; vat
End SubCode names work only for sheets in the workbook that contains the code (ThisWorkbook). For other workbooks, use the tab name and check it exists first.
Version control
Excel files are binary zip packages, so tools like Git cannot show what changed in your code. The solution is to export each module as a text file: right-click a module in the Project Explorer and choose Export File, which writes .bas (modules), .cls (classes) and .frm/.frx (forms). Commit those text files to Git or keep dated copies. Doing it by hand gets tedious, so many developers use a small macro:
Option Explicit
' Needs: File > Options > Trust Center > Trust Center Settings > Macro Settings >
' "Trust access to the VBA project object model" (Windows)
Sub ExportAllModules()
Dim comp As Object
Dim folder As String
Dim ext As String
folder = ThisWorkbook.Path & Application.PathSeparator & "src" & Application.PathSeparator
If Dir(folder, vbDirectory) = "" Then MkDir folder
For Each comp In ThisWorkbook.VBProject.VBComponents
Select Case comp.Type
Case 1: ext = ".bas" ' standard module
Case 2: ext = ".cls" ' class module
Case 3: ext = ".frm" ' UserForm
Case Else: ext = "" ' sheet and workbook modules: skipped here
End Select
If ext <> "" Then comp.Export folder & comp.Name & ext
Next comp
MsgBox "Modules exported to " & folder
End SubAt the very least, keep dated backups before big changes (SaveCopyAs, see Files and folders: open, save, loop through files and write text files).
Protecting the VBA project: what a password does and does not do
Under Tools > VBAProject Properties > Protection you can lock the project with a password so others cannot view the code. This is useful to stop casual edits and accidental breakage, but it is not security: the protection is weak and well-known tools remove it in seconds. Never rely on it to hide business secrets, and never let it replace proper access control on the file itself.
Never store passwords in code
It is tempting to write Const DB_PASSWORD = "Summer2026!" so a macro can log in to a database or a protected sheet. Anyone who opens the editor, or removes the weak project password, can read it, and it ends up in every copy and backup of the file. Better options:
- Ask the user for the password at run time and keep it only in a variable while the macro runs.
- Use Windows authentication (integrated security) for databases, so no password is needed.
- For sheet protection, accept that
Worksheet.Protectpasswords only prevent accidents, not determined users.
Digital signatures
A digital signature proves who wrote the macros and that they have not been changed since signing. With the macro setting "Disable VBA macros except digitally signed macros", only signed code from trusted publishers runs, which is the most secure setup for companies (What is VBA? Macros, when to use them and macro security).
- Get a certificate. Companies usually issue code-signing certificates from their own certificate authority or buy one. For personal use on your own computer, Windows Office includes SelfCert.exe (Digital Certificate for VBA Projects) in the Office installation folder; it creates a self-signed certificate.
- In the VBA editor choose Tools > Digital Signature > Choose and select the certificate.
- Save the workbook. The first time others open it, they can choose to trust you as a publisher.
A self-signed certificate is trusted only on the computer where it was created (unless others install it manually), so it is a convenience for your own files, not a way to vouch for code to strangers. If anyone edits the code later, the signature is removed when the file is saved and must be re-applied. On the Mac, Excel can run signed macros, but signing is done on Windows.
Trusted locations
Rather than enabling content file by file, an organisation can declare network folders as trusted locations (Trust Center > Trusted Locations). Files in them open with macros enabled. Keep such folders write-protected, so only maintainers can put code there; a trusted folder that everyone can write to is an open door.
Sharing your code
| Way to share | Good for | Notes |
|---|---|---|
| .xlsm workbook | A tool with its own data and sheets | Users must enable content or use a trusted location |
| .xlam add-in | Functions and ribbon commands used in many workbooks | Install once via File > Options > Add-ins > Go; code is shared, data stays in the users' files |
| Personal Macro Workbook | Your own everyday helpers | Only on your computer; not for sharing |
| Exported .bas files | Developers who want to import code | Import with File > Import File |
An add-in is a workbook saved as Excel Add-in (*.xlam). Its sheets are hidden, and its macros and user-defined functions (User-defined functions (UDFs): your own worksheet functions) are available in every workbook while it is loaded. In add-in code, ThisWorkbook means the add-in itself and ActiveWorkbook means the user's file, so be precise about which one you mean.
The Personal Macro Workbook (PERSONAL.XLSB) is created the first time you record a macro with "Store macro in: Personal Macro Workbook" (The macro recorder: record, read and clean up code). It opens hidden every time Excel starts, so its macros are always available to you. It lives in the XLSTART folder (Windows: %APPDATA%\Microsoft\Excel\XLSTART; Mac: inside ~/Library/Group Containers/UBF8T346G9.Office/User Content/Startup/Excel). Back it up; it is easy to lose when changing computers. Do not build tools that colleagues depend on into it, because they do not have your copy.
A checklist before you share a macro
Option Explicitin every module and Debug > Compile passes.- No
Select/Activatethat depends on what the user clicked last (Make your macros fast: speed optimization in VBA). - Error handling that restores settings and gives a clear message (Error handling and debugging in VBA).
- No hard-coded personal paths such as
C:\Users\Anna\Desktop; useThisWorkbook.Path, a Settings sheet or a folder picker. - No passwords or personal data in the code.
- Late binding (or no external references) if users have different Office versions.
- A short "How to use" note on the first sheet.
- Tested on a copy of real data, and on a Mac if Mac users will run it.
Check yourself
1. What does ticking Require Variable Declaration do?
The setting affects new modules only; add Option Explicit to existing modules yourself.
2. Why refer to a sheet by its code name, such as shData, instead of Worksheets("Data")?
Tab names change easily; the code name is set in the VBA editor and stays fixed.
3. How strong is a VBA project password?
Treat it as a lock against accidents, not as security. Never store secrets in code.
4. Where should a VBA tool that adds functions to every workbook for your team be stored?
An add-in is installed once and its functions and commands are available in every workbook.
5. What happens to a digital signature when someone changes the code and saves?
A signature guarantees the code is unchanged, so editing invalidates it.