VBA code generator
Describe what the macro should do. You get a complete Sub, and a warning where it cannot be undone.
A worked example
“Delete every completely blank row on Sheet1”
Sub DeleteBlankRows()
Dim ws As Worksheet
Dim lastRow As Long
Dim r As Long
Set ws = ThisWorkbook.Worksheets("Sheet1")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For r = lastRow To 2 Step -1
If Application.WorksheetFunction.CountA(ws.Rows(r)) = 0 Then
ws.Rows(r).Delete
End If
Next r
End SubIt finds the last used row in column A, then walks upwards deleting any row with nothing in it. The loop runs backwards because deleting a row shifts everything below it up, and a forward loop skips the row that moves into the gap.
What it assumes
- This cannot be undone with Ctrl+Z. Save a copy of the workbook before running it the first time.
- Starts at row 2, so a header row is never deleted. Change the 2 to a 1 if your sheet has no headers.
- Finds the last row from column A. If column A has gaps at the bottom but column F does not, rows below the last A value are never examined.
01
It names the sheet rather than trusting the active one.
Macros written against ActiveSheet work perfectly until the day somebody runs one with the wrong tab in front of them. Every sheet reference comes back qualified.
02
It warns you before it destroys anything.
A macro that deletes rows or overwrites cells cannot be undone with Ctrl+Z. Where that is true, it is the first caveat rather than a footnote.
03
Every variable is declared.
The code is written to run under Option Explicit, which is the setting that turns a mistyped variable name from a silent empty value into an error you can see.
Questions people ask
Where do I paste this?
Press Alt and F11 to open the VBA editor, then Insert and Module, and paste it there. Run it with F5, or from Developer and Macros in the ribbon.
Why does it warn me about undo?
Because Ctrl+Z does not reverse anything a macro did. Excel clears the undo stack when VBA runs. That surprises people exactly once, usually on a file they had not saved.
Will it work in Excel for Mac?
Mostly. Core VBA is the same, but file paths, some dialogs and anything touching Windows APIs differ. If the macro touches the file system, test it on a copy first.
Should I be using Office Scripts or Python instead?
If you are on Excel for the web, Office Scripts is the supported path. VBA remains the right answer for a desktop workbook that has to keep working on colleagues' machines without anything being installed.
Related
When it is a whole file
A formula fixes one column. If what you actually have is four exports and a question, drop them here and you get the cleaned data, the analysis and the charts back.
No account needed to start. You only pay when you like what you see.