尝试解决“Null 无效使用”问题在VBA中
首先快速片段:
Dim GUID As String
Dim givenNames, familyName, preferredName, gender, comments, carer, medicareNumber, patientNumber As String
Dim dob As Variant
Dim deceased, resolved, consultNotes As Boolean
Dim age As Variant
givenNames = Null
familyName = Null
preferredName = Null
gender = Null
dob = Null
comments = Null
deceased = False
resolved = False
carer = Null
age = Null
consultNotes = False
patientNumber = Null ' This is where I get the error
知道为什么最后一个变量会出错吗?我已将 Null 分配给一堆其他字符串,没有任何错误。
Quick snippet first:
Dim GUID As String
Dim givenNames, familyName, preferredName, gender, comments, carer, medicareNumber, patientNumber As String
Dim dob As Variant
Dim deceased, resolved, consultNotes As Boolean
Dim age As Variant
givenNames = Null
familyName = Null
preferredName = Null
gender = Null
dob = Null
comments = Null
deceased = False
resolved = False
carer = Null
age = Null
consultNotes = False
patientNumber = Null ' This is where I get the error
Any idea why this last variable would be the one to trip up? I've assigned Null to a bunch of other strings without any errors.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在VBA/VB6中,字符串不能设置为Null;只有 Variants 可以设置为 null。此外,当您像问题中那样声明内联逗号分隔的变量时,只有最后一个会被输入为字符串;所有其他的都被键入为变体。要将它们在一行上声明为一种类型,您必须包含该类型
,这就是为什么在一行上声明它们是有意义的。
(顺便说一句,应该注意的是,出于同样的原因,
deceeded,resolved
也被键入为变体。)In VBA/VB6, strings cannot be set to Null; only Variants can be set to null. In addition, when you declare variables inline comma-separated like in the question, only the last one will be typed as string; all of the others are typed as variants. To declare them on one line as a type you have to include the type
That's why it makes sense to just declare them on a single line.
(Btw, it should be noted that
deceased, resolved
are also typed as variants for the same reason.)它对
givenNames
等成功的原因是您无意中将它们定义为 Variant 类型。patentNumber
失败,因为您已成功将其定义为String
,并且字符串不接受 Null 值。在
Dim
语句中,As
子句适用于列表中的每个单独变量,因此通过仅将其放在列表末尾,您可以应用仅对最后列出的变量显式类型。Variant
的隐式类型应用于其他类型。The reason that it succeeds for
givenNames
, etc. is that you have unwittingly defined them as Variant type. It fails forpatientNumber
, because you successfully defined that as aString
, and strings do not accept Null values.Within a
Dim
statement, theAs <type>
clause applies to each individual variable in the list, so by putting it only at the end of the list, you applied the explicit type only to the last-listed variable. The implicit type ofVariant
is applied to the others.当我在不知道
Variant
的隐式类型的情况下遇到这个问题时,我可以使用在末尾定义一个额外变量的解决方法,例如BogusVariable
Dim
语句列表。When I ran into that problem without knowing about the implicit type of
Variant
, I was able to use the work around of defining an extra variable such asBogusVariable
at the end of theDim
statement list.在 VBA 字符串中,使用
vbNullString
值表示Null
in VBA strings uses
vbNullString
value forNull