在VBA中,有一种很好的方法来获取变量/对象的文本表示吗?就像Java的各种String.valueOf(...)方法一样。
答案 0 :(得分:4)
除了'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
答案 1 :(得分:1)
您尝试过:CStr(...)
?
答案 2 :(得分:0)
如果您需要将整数显示为十六进制、八进制或二进制,此代码适用于 Excel -
fmt = CStr(arg) & " - vbInteger" & " - &H" & Hex(arg) & " - &O" & Oct(arg) & " - &B" & WorksheetFunction.Dec2Bin(arg, 8)
输出看起来像这样
65 - vbInteger - &H41 - &O101 - &B01000001
如果您不使用 Excel,请尝试此站点 -
http://www.vb-helper.com/howto_net_dec_hex_oct_bin.html
函数 LongToBinary 返回一个值的二进制文本表示。