【问题标题】:When is the VBA CVar function actually useful?VBA CVar 函数何时真正有用?
【发布时间】:2018-11-14 09:59:29
【问题描述】:

VBA 根据需要将值隐式转换为Variant,那么CVar function 的用例是什么?在example given in the documentation 中,对CVar 的调用显然是多余的。

确切地说,我正在寻找一个具体的、最小的 VBA 代码示例,它

  • 编译,但是
  • 当(仅!)CVar(...some expression...)...some expression... 替换时,不会编译(或产生不同的输出)。

我找不到这样的例子,但也许其他人可以。

【问题讨论】:

    标签: vba language-lawyer


    【解决方案1】:

    我无法考虑以下内容的实际用法,但至少它表明您可能需要该功能:

    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
    

    【讨论】:

    • 一个很好,我希望它会提高编译时间 byref mismatch ,但它不会。但是这类问题一般是worked aroundCall testSub((myInt))
    • 在您的示例中,myInt 也作为Variant 传递,但with VT_BYREF() 删除该标志。这是一个有趣的主题,有有趣的结果,例如见stackoverflow.com/q/52686198/11683
    • @GSerg:出于好奇:您知道在 VBA 中读取 VT-Flags 的任何方法吗?
    • 是的,读取从VarPtr(that_variable) 开始的前两个字节。一个例子:stackoverflow.com/a/43554246/11683
    【解决方案2】:

    不确定这是否符合条件,但我唯一能想到的是在Declare 中与As Any 的交互。

    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
    

    【讨论】:

    • 不错的一个!我考虑过重载,但拒绝了这个想法,因为VBA本身不支持它,并且完全忘记了As Any的重载消费
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    相关资源
    最近更新 更多