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

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

问题描述

我如何定义一个空字符串,日期或整数VBA?

我需要能够在数据不完整或不相关分配一个空值的某些记录某些字段,但如果我声明一个变量为一个字符串,日期或整型,我得到的错误尝试分配一个空值时,

时使用变体唯一的解决办法?如果是这样,那么什么是所有其它数据类型的VBA点?

解决方案

 暗淡x As中变异
X =空
 

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

  

Variant是可以包含任何类型的数据的一种特殊的数据类型[...]一个变种还可以包含特殊值空,错误,没有什么,和

所有其他数据类型的点是precisely他们的不能的包含任何醇'类型的数据。这有两个好处,我能想到的:

  • 这是比较困难的程序员错误无意类型的数据分配给变量,因为这会在编译时被检测到。这可以帮助prevent的错误,让你和旁边的人谁将会保持你的code的东西更清晰。
  • 窄的数据类型节省存储空间。把整数在Variant(16字节)占用的方式更多的内存比将它们放在一个Int(2字节)。如果你有大的数组这将成为显著。

当然,变体也有自己的位置,在该网站的其他线程的讨论。

How do I define a Null string, date or integer in 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.

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

Only the Variant data type can hold the value 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:

  • 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.

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

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

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