I have two subs and want to pass values from one to the other.
Option Explicit
Sub Test()
Call HandleInput(ActiveSheet.Range("A1:C4"), 4, 2)
End Sub
Sub HandleInput(rng As Range, rowNumber As Long, colNumber As Long)
Debug.Print rng.Cells(rowNumber, colNumber).Value
End Sub
However, sometimes I want to apply the same routine over the same range, but with a different rownumber
and a different colnumber
. I could just call the sub again with the new values and right now that seems to be by far the easiest option, but I still want know if there's a smart way to handle it with optional parameters in HandleInput
:
Sub HandleInput(rng As Range, rowNumber As Long, colNumber As Long, Optional rowNumber2 As Long, _
Optional colNumber2 As Long, Optional rowNumber3 As Long, Optional colNumber3 As Long)
...
End Sub
This made me wonder:
Can I somehow tell VBA that, if rowNumber2
is being provided, a value for colNumber2
needs to be passed as well? I know I could try it with IsMissing()
and switching the data type to Variant
:
Sub HandleInput(rng As Range, rowNumber As Long, colNumber As Long, Optional rowNumber2 As Variant,
_ Optional colNumber2 As Variant, Optional rowNumber3 As Variant, Optional colNumber3 As Variant)
If Not IsMissing(rowNumber2) Then
If IsMissing(colNumber2) Then
MsgBox "Please enter a value for colNumber2."
End
End If
End If
End Sub
This requires lots of if-Statements, also in the other direction, (If NOT IsMissing(colNumber2) Then
). And it only gets worse if more than two variables should be tied together. Any calculation that I try as a workaround gives me an error ("Type mismatch") when one value is missing, for example I tried:
If IsError(rowNumber2 * colNumber2) Then
MsgBox "Error, please supply both rowNumber2 and colNumber2"
End If
Is there a native functionality for this? The only solution I came up with is supplying default values that I know won't occur "naturally":
Sub HandleInput(rng As Range, rowNumber As Long, colNumber As Long, Optional rowNumber2 As Long = -100, _
Optional colNumber2 As Long = -100, Optional rowNumber3 As Long = -100, Optional colNumber3 As Long = -100)
If rowNumber2 = -100 Or colNumber2 = -100 Then
MsgBox "Please enter a value for both rowNumber2 and colNumber2."
End
End If
End Sub