简体   繁体   English

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

[英]What is the difference between VBA.Str and VBA.Str$?

What is the difference between these two code lines 这两条代码行有什么区别

Debug.Print VBA.Str(123) 

and

Debug.Print VBA.Str$(123)

Str$ and Str are identical except for at least 2 important differences: Str$Str相同,但至少有两个重要区别:

  1. If the usage of Str$ returns anything other than a String, you'll get an error: 如果Str$的使用返回的不是字符串,则返回错误:

     Debug.Print Str(Null) 'Prints Null Debug.Print Str$(Null) 'Throws Runtime Error 94 - Invalid use of Null 
  2. Str$ returns a String, whereas Str returns a Variant. Str$返回一个String,而Str返回一个Variant。 In general, you should always prefer the strongly typed Str$ over Str 通常,您应始终首选强类型Str$不是Str

There are many other functions that use $ -suffixes, like Left$ , Mid$ and Space$ . 还有许多其他使用$后缀的函数,例如Left$Mid$Space$

If we look at Left$ (which is really just an alias for _stdcall _B_str_Left ) and Left (which is really just an alias for _stdcall _B_var_Left ), in the Type Library MIDL, we see that the input types matter too . 如果在类型库MIDL中查看Left$ (实际上只是_stdcall _B_str_Left的别名)和Left (实际上只是_stdcall _B_var_Left的别名),我们会发现输入类型也很重要

[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);

You can actually use the underlying functions in code: 您实际上可以在代码中使用基础功能:

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

And to make matters more confusing, a function like Join (that does return a String, but which doesn't have a corresponding Join$ function, can actually be used with a $ suffix: 使事情更加混乱,像函数Join (即不会返回一个字符串,但没有相应的Join$功能,实际上可以 使用$后缀:

Debug.Print Join$(Array(1, 2, 3), ".") 'Prints 1.2.3

For further discussion, see my answer at Exactly what are these _B_var_Xxxxx and _B_str_Xxxxx members in the VBA COM libraries? 有关进一步的讨论,请参阅我的答案, 确切地说,VBA COM库中的这些_B_var_Xxxxx和_B_str_Xxxxx成员是什么?

Str$ is identical to Str except for the declared type of its return value. 除了声明的返回值类型以外,Str $与Str相同。 ie Str returns a Variant, the Str$ returns a String. 即Str返回一个Variant,Str $返回一个String。

Refer the msdn link 参考msdn链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM