尝试解决 VBA 中的“无效使用 Null”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5630743/
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
Trying to resolve an "invalid use of Null" in VBA
提问by HorusKol
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.
知道为什么最后一个变量会绊倒吗?我已将 Null 分配给一堆其他字符串,没有任何错误。
回答by Thomas
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
在 VBA/VB6 中,字符串不能设置为 Null;只有 Variants 可以设置为 null。此外,当您像问题中一样声明内联逗号分隔的变量时,只有最后一个会被输入为字符串;所有其他的都被输入为变体。要将它们在一行上声明为一种类型,您必须包含该类型
Dim a As String, Dim b As String ...
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.)
(顺便说一句,应该注意的deceased, resolved
是,出于同样的原因,它们也被键入为变体。)
回答by Steve Jorgensen
The reason that it succeeds for givenNames
, etc. is that you have unwittingly defined them as Variant type. It fails for patientNumber
, because you successfully defined that as a String
, and strings do not accept Null values.
它成功的原因givenNames
是你在不知不觉中将它们定义为 Variant 类型。它失败了patientNumber
,因为您成功地将其定义为 a String
,并且字符串不接受 Null 值。
Within a Dim
statement, the As <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 of Variant
is applied to the others.
在Dim
语句中,该As <type>
子句适用于列表中的每个单独变量,因此通过将其仅放在列表的末尾,您将显式类型仅应用于最后列出的变量。的隐式类型Variant
应用于其他类型。
回答by Darrell
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 as BogusVariable
at the end of the Dim
statement list.
当我在不知道 的隐式类型的情况下遇到这个问题时Variant
,我能够使用解决方法来定义一个额外的变量,例如BogusVariable
在Dim
语句列表的末尾。