在公式中使用变量前必须声明它。变量可以保持某个给定类型的值。允许的类型是七种简单类型(数字、货币、字符串、布尔值、日期、时间和日期时间),六种范围类型(数字范围、货币范围、字符串范围、日期范围、时间范围和日期时间范围)以及保持上述类型数组的变量。这为变量提供了总共 26 种不同的类型。
声明变量时,还指定了它的名称。变量不能与任何对 Basic 语法有效的函数、运算符或其他关键字同名。例如,变量不能被命名为 Sin、Mod 或 If,因为 Sin 是内置函数,Mod 是内置运算符,而 If 是内置关键字。当在公式编辑器中键入公式时,内置函数、运算符或其他关键字的名称均以不同的颜色突出显示,因此很容易检查出变量名是否与它们冲突。
变量一经声明后,即可在公式中使用。例如,可能希望为其赋以一个初始值:
Dim x As Number 'Declare x to be a Number variable x = 10 'Assign the value of 10 to x
在一个语句中可以通过将变量声明用逗号分开来声明多个变量:
Dim x As Number, y as String, z as DateTime Range x = 10 : y = "hello" z = #Jan 1, 1999# To #Jan 31, 1999#
通常情况下,声明变量时不需要显式给定其类型。在这种情况下,变量类型在第一次向其赋值时确定。这与特殊变量 formula 相似。这与 Visual Basic 有所不同,在 Visual Basic 中,声明时没有给定类型的变量将自动成为 Variant 类型。但实际上,这意味着可以用与在 Visual Basic 中使用 Variant 时相似的样式编写公式。
Dim p 'The type of p is not known yet p = "bye" 'The type of p is now set to be String Dim q 'The type of q is not known yet q = Array ("hello", p) 'q is a String Array 'Error- p is a String variable and cannot hold a Number p = 25 Dim r 'r is a Number variable, and holds the value 5 r = (10 + 5) / 3 'The types of a and c are not known yet Dim a, b As Boolean, c b = False 'The type of a is now set to Boolean 'and its value is False a = b 'The type of c is now set to Number and its value is 17 c = 2 + 3 * 5
声明和初始化范围变量的示例
Dim gradeA, quarter 'The type of gradeA is set to Number Range gradeA = 90 To 100 'The type of quarter is set to Date Range quarter = CDate (1999, 10, 1) To CDate (1999, 12, 31)