vba 未定义字符类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28623732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Char type not defined
提问by Marian Becheru
Dim myChar As Char
throws Compile Error: "User-defined type not defined"
抛出编译错误:“未定义用户定义的类型”
What reference should I include to use Char type?
我应该包括什么参考来使用 Char 类型?
回答by Wiktor Stribi?ew
Char
type does not exist in VBA, you should use String
instead.
Char
VBA 中不存在类型,您应该使用它String
。
Dim myChar As String
Note that VBA is not the same as VB.NET. In VB.NET, you can use Char
.
请注意,VBA 与 VB.NET 不同。在 VB.NET 中,您可以使用Char
.
EDIT: Following Micha? Krzych's suggestion, I'd use fixed-length string for this specific purpose.
编辑:跟随米查?Krzych 的建议,我会为此特定目的使用固定长度的字符串。
Dim myChar As String * 1
Here is an excerpt from "VBA Developer's Handbook" by Ken Getz and Mike Gilbert:
以下是Ken Getz 和 Mike Gilbert 撰写的“VBA 开发人员手册”的摘录:
"Dynamic strings require a bit more processing effort from VBA and are, accordingly, a bit slower to use." ... "When working with a single character at a time, it makes sense to use a fixed-length string declared to contain a single character. Because you know you'll always have only a single character in the string, you'll never need to trim off excess space. You get the benefits of a fixed-length string without the extra overhead."
“动态字符串需要 VBA 进行更多的处理工作,因此使用起来要慢一些。” ...“当一次处理单个字符时,使用声明为包含单个字符的固定长度字符串是有意义的。因为您知道字符串中始终只有一个字符,所以您将永远不需要修剪多余的空间。您可以获得固定长度字符串的好处,而无需额外开销。”
One caveat to this is that fixed string notation is NOT allowed in functions and subroutines;
对此的一个警告是,函数和子例程中不允许使用固定字符串表示法;
Sub foo (char as string *1) 'not allowed
Sub foo (char as string *1) '不允许
...
...
End Sub
结束子
So you would either need to use;
所以你要么需要使用;
Sub foo (char as string) 'this will allow any string to pass
Sub foo (char as string) '这将允许任何字符串通过
or
或者
Sub foo (char as byte) 'the string would need to be converted to work
Sub foo (char as byte) '需要将字符串转换为工作
One thing to be careful of when using bytes is that there is no standard whether a byte is unsigned or not. VBA uses unsigned bytes, which is convenient in this situation.
使用字节时要注意的一件事是字节是否无符号没有标准。VBA 使用无符号字节,在这种情况下很方便。
回答by Alex P
I think it depends how you intend to use it:
我认为这取决于您打算如何使用它:
Sub Test()
Dim strA As String, strB As Byte, strC As Integer, strD As Long
strA = "A"
strB = 65
strC = 75
strD = 90
Debug.Print Asc(strA) '65
Debug.Print Chr(strB) 'A
Debug.Print Chr(strC) 'K
Debug.Print Chr(strD) 'Z
End Sub