VBA Macro Arguments
Written by Rod Wing.
MicroStation VBA allows for supplying arguments in a macro call, most other VBA implementations including the Microsoft Office apps to do not support this feature. The arguments are stored as a single string in the application’s KeyinArguments property. Multiple arguments must be parsed by the program prior to use.
Using arguments to call a macro allows for much more flexibility, such as allowing for variable inputs for use in a Batch Process script. The following macro illustrates how arguments can be parsed. In the case of this macro all of the arguments must be separated by spaces.
vba run MacroWithArguments arg1 arg2 arg3
Sub MacroWithArguments()
Dim strArgs() As String
Dim i As Long
Dim iStart As Long
Dim iEnd As Long
If Len(KeyinArguments) > 0 Then
'
' Arguments separated by spaces
'
strArgs = Split(KeyinArguments, " ")
iStart = LBound(strArgs)
iEnd = UBound(strArgs)
For i = iStart To iEnd
Debug.Print strArgs(i)
Next
End If
End Sub
Here is an example of how this could be put to use. This PlaceCell macro will open a userform if no arguments are supplied. It also allows the arguments to be supplied in any order by using the command switches (-n, -s, -a, etc.)
Usage: vba run PlaceCell -n<cellName> -s<cellScale> -a<cellAngle> -x<xValue> -y<yValue> -z<zValue>
Sub PlaceCell()
Dim strArgs() As String
Dim i As Long
Dim iStart As Long
Dim iEnd As Long
Dim cellName As String
Dim cellScale As String
Dim cellAngle As String
Dim strSwitch As String
Dim x As String
Dim y As String
Dim z As String
'
' Set default values for arguments not supplied
'
cellName = ActiveSettings.cellName
cellScale = cStr(ActiveSettings.Scale.x)
cellAngle = cStr(Degrees(ActiveSettings.Angle))
x = "0"
y = "0"
z = "0"
If Len(KeyinArguments) = 0 Then
'
' No arguments - show user form
'
UserForm1.Show
Else
'
' Arguments supplied - run in batch mode
'
strArgs = Split(KeyinArguments, " ")
iStart = LBound(strArgs)
iEnd = UBound(strArgs)
For i = iStart To iEnd
strSwitch = Left$(strArgs(i), 2)
Select Case strSwitch
Case "-n"
cellName = Mid$(strArgs(i), 3)
Case "-s"
cellScale = Mid$(strArgs(i), 3)
Case "-a"
cellAngle = Mid$(strArgs(i), 3)
Case "-x"
x = Mid$(strArgs(i), 3)
Case "-y"
y = Mid$(strArgs(i), 3)
Case "-z"
z = Mid$(strArgs(i), 3)
End Select
Next
With CadInputQueue
.SendKeyin "active cell " & cellName
.SendKeyin "active scale " & cellScale
.SendKeyin "active angle " & cellAngle
.SendKeyin "place cell icon"
.SendDataPoint Point3dFromXYZ(CDbl(x), CDbl(y), CDbl(z))
End With
End If
End Sub
Tags: VBA