变量Variable

定义变量

基本格式

Dim 变量名 As 数据类型

样例

1
Dim Price As Currency

变量名命名规范

全小写,每个单词首字母大写

1 2 3
Dim Price As CurrencyDim SpecialDiscount As DoubleDim TotalAmount As Integer

对于循环时的一个字母的变量,用小写

1
Dim i As Integer

大小写不敏感

VBA 中 大小写不一样,拼写一样的变量,会被自动纠正为同样的大小写,并报错

1 2! < <
Dim Price As CurrencyDim price As CurrencyCompile error:Duplicate declaration in current scope
广告

数据类型

在 VBA 中,定义变量时,需要想清楚,你希望计算机帮助你存储什么样的数据

表达整数

类型范围
Byte0 ~ 255
Integer-32,768 ~ 32,767
Long差不多 2109-2 \cdot 10^9 ~ 21092 \cdot 10^9
LongLong差不多 91018-9 \cdot 10^{18} ~ 910189 \cdot 10^{18}

如果你计算过程中超过定义时的范围,就会出现一些问题

一般用 Long

表达小数

类型描述
Single精度略低
Double精度较高
Currency保留 4 位小时,金额相关首选
Decimal精度超高、计算时超慢

其它类型

类型描述
BooleanTrue 或 False 用于存储 对错
String字符串 用于 存储 文字
Date日期

对象类型

也可以 系统或用户 的自定义类型

1
Dim SheetA As Sheet
广告

使用变量

赋值

1 2 3 4 5
Dim Name As String Name = "ZZAX 文档" Dim Port As Integer Port = 9917

取值

1 2 3 <
Dim Price As Currency Price = 998Debug.Print Price998

使用前也可以不声明

1 2 <
Price = 998Debug.Print Price998

会正常运行,但是这样会对代码造成维护性的隐患

广告

ZZAX 微信公众

文档一更新,立刻告诉你