When is the VBA CVar function actually useful?

Viewed 90

VBA implicitly converts values to Variant as needed, so what would be a use case of the CVar function? In the example given in the documentation, the call to CVar is obviously redundant.

To be precise, I am looking for a concrete, minimal VBA code example, which

  • compiles, but
  • won't compile (or produce a different output) when (only!) CVar(...some expression...) is replaced by ...some expression....

I haven't been able to find such an example, but maybe the someone else can.

2 Answers

I cannot think about a real life usage for the following, but at least it shows that you could need the function:

Sub test()
    Dim myInt As Integer
    myInt = 2
    ' The following call will throw a runtime error in testSub
    Call testSub(myInt)   
    ' That's okay
    Call testSub(CVar(myInt))
End Sub

Sub testSub(ByRef p As Variant)
    Debug.Print "P: " & VarType(p)
    p = "ABC"
End Sub

Not sure if that qualifies, but the only thing I can think of is the interaction with As Any in Declare.

Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
  (Destination As Any, source As Any, ByVal Length As Long)

Sub Test()
  Dim source As Long, dest As Long

  source = 42

  CopyMemory dest, CVar(source), 4
  MsgBox dest

  CopyMemory dest, source, 4
  MsgBox dest
End Sub
Related