Expert guide
Using AI to Write Excel VBA Macros Safely
Prompts that produce working code, and a review checklist before you press Run
Call us at +1 (385) 386-3860
Short answer: AI tools write usable Excel VBA when you describe exact sheet names, columns, steps and failure cases, and ask for Option Explicit, comments and error handling. Read the code before running it, test on a copy, and look for destructive lines such as Delete, Kill, SaveAs and ClearContents. For macros other people depend on, have them reviewed or built by an Excel developer.
VBA is old, but it is still the fastest way to automate the desktop Excel work that fills an operations team's week: formatting exports, splitting a master sheet into one file per branch, merging files from a folder, emailing reports. AI has made VBA accessible to people who never learned it. It has also made it easy to run code nobody has read on files that matter.
This guide shows how to get good VBA out of ChatGPT, Claude, Gemini or Copilot, and how to review it in ten minutes even if you are not a programmer.
Start With a Specification, Not a Wish
"Write a macro to clean my report" produces generic code. A short specification produces code that runs on your file. Use this template:
Platform: Excel 365 on Windows.
Workbook: "Weekly Sales.xlsm".
Input: sheet "Export", headers in row 1, data from row 2.
A = Branch, B = Invoice No, C = Date, D = Customer, E = Amount.
Task:
1. Delete rows where Amount is blank or zero.
2. Sort by Branch, then Date (oldest first).
3. For each Branch, copy its rows to a new workbook and save it as
"Sales - <Branch> - <yyyy-mm-dd>.xlsx" in the same folder.
Rules:
- Use Option Explicit and declare every variable.
- Do not modify the original file; work on a copy of "Export".
- If sheet "Export" is missing, show a message and stop.
- Ask for confirmation before saving files.
- Comment each block in plain English.What Good AI-Written VBA Looks Like
Here is the shape of a macro you should expect back from a prompt like the one above. Notice the safety checks before any work starts.
Option Explicit
Sub SplitSalesByBranch()
Dim ws As Worksheet, wsWork As Worksheet
Dim lastRow As Long, r As Long
Dim branches As Object, b As Variant
Dim newWb As Workbook, outPath As String
On Error GoTo Fail
' 1. Make sure the input sheet exists
On Error Resume Next
Set ws = ThisWorkbook.Worksheets("Export")
On Error GoTo Fail
If ws Is Nothing Then
MsgBox "Sheet 'Export' not found.", vbExclamation
Exit Sub
End If
If MsgBox("Create one file per branch in " & ThisWorkbook.Path & "?", _
vbYesNo + vbQuestion) <> vbYes Then Exit Sub
Application.ScreenUpdating = False
' 2. Work on a copy so the original export is untouched
ws.Copy After:=ws
Set wsWork = ActiveSheet
wsWork.Name = "Work_" & Format(Now, "hhmmss")
' 3. Remove blank / zero amounts (loop bottom-up when deleting)
lastRow = wsWork.Cells(wsWork.Rows.Count, "A").End(xlUp).Row
For r = lastRow To 2 Step -1
If Val(wsWork.Cells(r, "E").Value) = 0 Then wsWork.Rows(r).Delete
Next r
' 4. Collect distinct branches
Set branches = CreateObject("Scripting.Dictionary")
lastRow = wsWork.Cells(wsWork.Rows.Count, "A").End(xlUp).Row
For r = 2 To lastRow
branches(CStr(wsWork.Cells(r, "A").Value)) = True
Next r
' 5. Filter and export each branch
For Each b In branches.Keys
wsWork.Range("A1").CurrentRegion.AutoFilter Field:=1, Criteria1:=b
Set newWb = Workbooks.Add(xlWBATWorksheet)
wsWork.Range("A1").CurrentRegion.SpecialCells(xlCellTypeVisible) _
.Copy newWb.Worksheets(1).Range("A1")
outPath = ThisWorkbook.Path & Application.PathSeparator & _
"Sales - " & b & " - " & Format(Date, "yyyy-mm-dd") & ".xlsx"
newWb.SaveAs outPath, FileFormat:=xlOpenXMLWorkbook
newWb.Close SaveChanges:=False
Next b
wsWork.AutoFilterMode = False
Application.DisplayAlerts = False
wsWork.Delete
Application.DisplayAlerts = True
Done:
Application.ScreenUpdating = True
MsgBox branches.Count & " branch files created.", vbInformation
Exit Sub
Fail:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "Stopped: " & Err.Description, vbCritical
End SubTwo details separate this from the code AI often returns on a vague prompt: it deletes rows from the bottom up (deleting top-down skips rows), and it restores ScreenUpdating and DisplayAlerts even when an error occurs. Without that, a failed macro can leave Excel silently suppressing every warning for the rest of the session.
The 10-Minute Review Checklist
You do not need to understand every line. You do need to find the lines that can do damage.
Search for destructive keywords
Delete, Kill, ClearContents, Clear, SaveAs, Close SaveChanges:=True, RmDir. Confirm each one acts on what you expect.
Check every hard-coded name
Sheet names, file paths and column letters must match your file exactly, including spaces.
Check loops have an end
Do While loops without a clear exit condition can freeze Excel. For-Next loops over Rows.Count can run a million times.
Look for error handling
On Error Resume Next with nothing after it hides every failure. It should be switched back with On Error GoTo.
Check what it opens or sends
Any code that sends email, calls a URL, or writes outside the workbook's folder deserves a second look.
Run on a copy, step through with F8
Press F8 in the VBA editor to run one line at a time and watch what happens.
Errors AI-Written VBA Hits Most Often
| Error | What it means | Usual fix |
|---|---|---|
| Run-time error 9: Subscript out of range | A sheet or workbook name does not exist | Correct the name or look it up safely |
| Run-time error 1004 | Excel refused an action (bad range, protected sheet, invalid file name) | Check the range, unprotect, remove illegal characters from file names |
| Run-time error 91: Object variable not set | Code used an object that was never found, often after Find | Test If rng Is Nothing before using it |
| Compile error: Variable not defined | Option Explicit caught an undeclared or misspelled variable | Declare it with Dim, or fix the spelling |
| Type mismatch (13) | Text where a number or date was expected | Clean the data or convert with CLng, CDbl, CDate |
When you hit an error, paste the exact message, the highlighted line, and a description of the data back into the chat. "It doesn't work" gets a guess; the error text gets a fix.
Prompts for Reviewing Code You Already Have
AI is just as useful for understanding inherited macros as for writing new ones. Many businesses run on VBA written by someone who left years ago.
Explain what this macro does step by step, and list anything it deletes, overwrites or sends.
Add comments to this code without changing its behaviour.
Add error handling so that ScreenUpdating and DisplayAlerts are always restored.
This macro is slow on 50,000 rows. Rewrite it to use arrays instead of reading cells one at a time.
Make this macro work on both Windows and Mac Excel, or tell me which parts cannot.
AI Prompting vs a VBA Developer
| Feature | AI-written macro | Developer-built automation |
|---|---|---|
| Cost | Free or subscription | Fixed project fee |
| Speed for a simple task | Minutes | Days |
| Handles messy real data | Only what you described | Tested against your actual files |
| Error handling and logging | If you asked for it | Standard |
| Works when layouts change | Often breaks | Designed for it |
| Documentation and support | None | Included |
Use AI for personal, low-risk macros. When a macro becomes part of how the business runs, treat it as software. We review, harden and rebuild VBA as fixed-scope work through our Excel development services, and for multi-step processes that span email, files and other systems, through AI workflow automation. If your problem is formulas rather than macros, start with using ChatGPT to write Excel formulas.
FAQ
AI and Excel VBA FAQ
Questions teams ask before trusting AI-written macros