Visual Basic for Applications:
Reading command line arguments

How to:

Unlike more straightforward programming environments, VBA doesn’t have a built-in feature to directly read command line arguments in a conventional sense because it’s primarily designed for embedding within Microsoft Office applications. However, with a bit of creativity, we can use Windows Script Host (WSH) or call external APIs to achieve similar functionality. Here’s a practical workaround using WSH:

  1. Create a VBScript to Pass Arguments to VBA:

    First, write a VBScript file (yourScript.vbs) that launches your VBA application (e.g., an Excel macro) and passes the command line arguments:

Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Open "C:\YourMacroWorkbook.xlsm"
objExcel.Run "YourMacroName", WScript.Arguments.Item(0), WScript.Arguments.Item(1)
objExcel.Quit
  1. Access the Arguments in VBA:

    In your VBA application (YourMacroWorkbook.xlsm), modify or create the macro (YourMacroName) to accept parameters:

Sub YourMacroName(arg1 As String, arg2 As String)
    MsgBox "Argument 1: " & arg1 & " Argument 2: " & arg2
End Sub
  1. Run Your Script:

    Execute the VBScript from the command line, passing arguments as needed:

cscript yourScript.vbs "Hello" "World"

This should result in your VBA macro being executed with the arguments “Hello” and “World”, displaying them in a message box.

Deep Dive:

In the historical context, VBA was devised to extend the capabilities of Microsoft Office applications, not as a standalone programming environment. As such, direct interaction with the command line is outside its primary scope, which explains the lack of built-in support for reading command line arguments.

The method outlined above, while effective, is more of a workaround than a native solution, leveraging external scripting to bridge the gap. This approach can introduce complexity and potential security concerns as it requires enabling macros and potentially lowering security settings to execute.

For tasks heavily reliant on command line arguments or needing more seamless integration with the Windows operating system, other programming languages like PowerShell or Python might offer more robust and secure solutions. These alternatives provide direct support for command line arguments and are better suited for standalone applications or scripts that require external input to modify their behavior dynamically.