VBA 中变量的空值 [英] Null values for variables in VBA

查看:102
本文介绍了VBA 中变量的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

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

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

推荐答案

Dim x As Variant
x = Null

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

Only the Variant data type can hold the value Null.

Variant 是一种特殊的数据类型,可以包含任何类型的数据 [...] Variant 还可以包含特殊值 Empty、Error、Nothing 和 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.

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

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

  • 程序员更难将非预期类型的​​数据错误地分配给变量,因为这会在编译时被检测到.这可以帮助防止错误并使您和下一个将维护您的代码的人更清楚.
  • 窄数据类型可节省存储空间.将整数放入 Variant(16 字节)比放入 Int(2 字节)占用更多内存.如果您有大型数组,这将变得很重要.

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

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

这篇关于VBA 中变量的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆