有没有一种通用的方法可以在 VBA 中获得一个很好的变量文本表示?

Hen*_*ler 5 vba

在 VBA 中,是否有一种很好的方法来获取变量/对象的文本表示?就像 Java 的各种 String.valueOf(...) 方法一样。

jto*_*lle 5

除了“CStr”之外没有任何内置内容,它具有您已经注意到的局限性。你唯一能做的就是自己写。幸运的是,VBA 有足够多的内置运算符('IsArray'、IsNumeric'、'VarType' 等)来简化操作。(这确实让你想知道,“为什么不让 'CStr' 更强大?”...)

下面的函数是一个例子。它们用于 Excel/VBA 代码,因此您可能不关心其中调用的用于格式化数组等的例程的实现,但它们应该为您提供基本概念。

'Diagnostic formatting of variant as string
Public Function fmt(arg) As String
    If IsObject(arg) Then
        fmt = fmtObj_(arg)
    ElseIf IsArray(arg) Then
        fmt = fmtArr_(arg)

    'Note that this test must come after IsArray() since IsMissing() returns
    'True for an empty array parameter (created by calling Array())
    ElseIf IsMissing(arg) Then
        fmt = "<Missing>"
    Else
        Select Case VarType(arg)
            Case vbDouble

                'Since we're in Excel, don't include double type char (#)
                fmt = CStr(arg)
            Case vbString
                fmt = """" & arg & """"
            Case vbEmpty
                fmt = "<Empty>"
            Case vbBoolean, vbDate
                fmt = CStr(arg)
            Case vbError
                fmt = fmtExcelVBAError_(arg)
            Case vbLong
                fmt = CStr(arg) & "&"
            Case vbInteger
                fmt = CStr(arg) & "%"
            Case vbCurrency
                fmt = CStr(arg) & "@"
            Case vbNull
                fmt = "<Null>"
            Case Else
                fmt = "<Typename - " & TypeName(arg) & ">"
        End Select
    End If

    If Len(fmt) > MAX_FMT_LEN_ Then
        fmt = Left$(fmt, MAX_FMT_LEN_) & " <...>"
    End If
End Function


'As fmt(), but "normal" conversion for strings, numbers, and Empty
Public Function toStr(arg) As String
    If IsObject(arg) Then
        toStr = fmt(arg)
    Else
        If VarType(arg) = vbString Or VarType(arg) = vbEmpty Or IsNumeric(arg) Then
            toStr = CStr(arg)
        Else
            toStr = fmt(arg)
        End If
    End If
End Function
Run Code Online (Sandbox Code Playgroud)