VBA.Str和VBA.Str $有什么区别?

时间:2016-10-19 06:41:07

标签: vba

这两个代码行之间有什么区别

Debug.Print VBA.Str(123) 

Debug.Print VBA.Str$(123)

2 个答案:

答案 0 :(得分:2)

Str$Str相同,但至少有两个重要差异:

  1. 如果Str$的使用返回String以外的任何内容,则会出错:

    Debug.Print Str(Null)   'Prints Null
    Debug.Print Str$(Null)  'Throws Runtime Error 94 - Invalid use of Null
    
  2. Str$返回一个String,而Str返回一个Variant。一般情况下,您应该始终更喜欢强类型Str$而不是Str

  3. 还有许多其他功能使用$ - 后缀,例如Left$Mid$Space$

    如果我们查看Left$(实际上只是_stdcall _B_str_Left的别名)和Left(实际上只是_stdcall _B_var_Left的别名),请参阅类型Library MIDL,我们看到输入类型也很重要

    [entry(616), helpcontext(0x000f6ea1)]
    BSTR _stdcall _B_str_Left(
                    [in] BSTR String, 
                    [in] long Length);
    [entry(617), helpcontext(0x000f653e)]
    VARIANT _stdcall _B_var_Left(
                    [in] VARIANT* String, 
                    [in] long Length);
    

    您实际上可以在代码中使用基础函数:

    Debug.Print VBA.Strings.[_B_var_Left]("abc",1) 'Prints a
    Debug.Print VBA.Strings.[_B_str_Left]("abc",1) 'Prints a
    

    更令人困惑的是,像Join这样的函数( 返回一个字符串,但没有具有相应的{{1}函数,可以实际使用 Join$后缀:

    $

    有关进一步的讨论,请参阅Exactly what are these _B_var_Xxxxx and _B_str_Xxxxx members in the VBA COM libraries?

    上的答案

答案 1 :(得分:0)

除了声明的返回值类型之外,Str $与Str相同。即Str返回Variant,Str $返回一个String。

参考msdn link