VBA 中变量的空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5630961/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:21:30  来源:igfitidea点击:

Null values for variables in VBA

vbaaccess-vba

提问by HorusKol

How do I define a Null string, date or integer in VBA?

如何在 VBA 中定义空字符串、日期或整数?

I need to be able to assign a Null value to some fields for certain records when data is incomplete or irrelevant, but if I declare a variable as a String, Date or Integer, I get errors when trying to assign a Null value.

当数据不完整或不相关时,我需要能够为某些记录的某些字段分配 Null 值,但是如果我将变量声明为字符串、日期或整数,则在尝试分配 Null 值时会出错。

Is the only solution to use Variant? If so, then what is the point of all other datatypes in VBA?

是使用 Variant 的唯一解决方案吗?如果是这样,那么 VBA 中所有其他数据类型的意义何在?

回答by Jean-Fran?ois Corbett

Dim x As Variant
x = Null

Only the Variant data type can hold the value Null.

只有 Variant 数据类型可以保存值Null

A Variant is a special data type that can contain any kind of data [...] A Variant can also contain the special values Empty, Error, Nothing, and Null.

Variant 是一种特殊的数据类型,可以包含任何类型的数据 [...] Variant 还可以包含特殊值 Empty、Error、Nothing 和Null

The "point" of all the other data types is precisely that they cannotcontain any ol' kind of data. This has two advantages that I can think of:

所有其他数据类型的“重点”正是它们不能包含任何类型的数据。这有两个我能想到的优点:

  • It's more difficult for the programmer to assign data of an unintended type to the variable by mistake, since this will be detected at compile time. This can help prevent bugs and make things clearer for you and the next person who will be maintaining your code.
  • Narrow data types save storage space. Putting integers in a Variant (16 bytes) takes up way more memory than putting them in an Int (2 bytes). This becomes significant if you have large arrays.
  • 程序员更难将非预期类型的​​数据错误地分配给变量,因为这会在编译时被检测到。这可以帮助防止错误并使您和下一个将维护您的代码的人更清楚。
  • 窄数据类型节省存储空间。将整数放入 Variant(16 字节)比放入 Int(2 字节)占用更多内存。如果您有大型数组,这将变得很重要。

Of course, Variants do have their place, as other threads on this site discuss.

当然,变体确实有其一席之地,正如本网站上的其他主题所讨论的那样。