一、VBA变量
1、变量是一个指定的内存位置,用于保存脚本执行过程中可以更改的值。以下是命名变量的基本规则。
- 变量名称必须使用一个字母作为第一个字符。
- 变量名称不能使用空格,句点(
.
),感叹号(!
)或字符@
,&
,$
,#
。 - 变量名称的长度不能超过
255
个字符。 - 不能使用Visual Basic保留关键字作为变量名称。/2变量使用前必须声明:
2、在VBA中,变量需要在使用它们之前声明。
Dim <<variable_name>> As <<variable_type>>
3、变量数据类型:主要分数字和非数字两种类型
- 数字数据类型
- 非数字数据类型
示例:
Private Sub VariablesDemo()
Dim password As String
password = "123456"
Dim num As Integer
num = 1234
Dim Name As String
Name = "Arron"
Dim BirthDay As Date
BirthDay = DateValue("1991-06-29")
MsgBox ("设置的密码是:" & password & Chr(10) & "num的值是:" & num & Chr(10) & "Name的值是:" & Name & Chr(10) & "Birthday的值是:" & BirthDay)
End Sub
结果如下:
二、VBA常量 Const
常量是一个命名的内存位置,用于保存脚本执行期间固定(无法更改)的值。如果用户试图更改常量值,则脚本执行结束时会出现错误。常量声明与声明变量相同。
以下是命名常量的规则 -
- 常量名称必须使用一个字母作为第一个字符。
- 常量名称不能在名称中使用空格,句点(
.
),感叹号(!
)或字符@
,&
,$
,#
。 - 常量名称的长度不能超过
255
个字符。 - 不能使用Visual Basic保留关键字作为常量名称。
语法:
Const <<constant_name>> As <<constant_type>> = <<constant_value>>
Private Sub ConstantDemo()
Const MyInteger As Integer = 720
Const myDate As Date = #10/21/2000#
Const myDay As String = "Sunday"
MsgBox ("整数值是:" & MyInteger & Chr(10) & "myDate的值是:" & myDate & Chr(10) & "myDay 的值是:" & myDay)
End Sub
注意:常量无法重新赋值
三、VBA运算符
运算符可以用一个简单的表达式定义,例如:4 + 5
等于9
。这里,4
和5
称为操作数,+
被称为运算符。VBA支持以下类型的运算符 -
- 算术运算符
- 比较运算符
- 逻辑(或关系)运算符
- 连接运算符
1、算术运算符
2、比较运算符
3、逻辑运算符
4、链接操作符
四、VBA决策
决策允许程序员控制脚本或其中一个部分的执行流程。执行由一个或多个条件语句控制。
以下是在大多数编程语言中找到的典型决策结构的一般形式。
1、if语句
Private Sub if_demo_Click()
Dim x As Integer
Dim y As Integer
x = 234
y = 32
If x > y Then
MsgBox ("X 的值大于 Y 的值")
End If
End Sub
2、if...else
Private Sub if_demo_Click()
Dim x As Integer
Dim y As Integer
x = 10
y = 20
If x > y Then
MsgBox ("X 的值大于 Y 的值")
Else
MsgBox ("Y 的值大于 X 的值")
End If
End Sub
3、else...if
Private Sub if_demo_Click()
Dim x As Integer
Dim y As Integer
x = 10
y = 10
If x > y Then
MsgBox ("X 大于 Y 的值")
ElseIf y > x Then
MsgBox ("Y 大于 X 的值")
Else
MsgBox ("X 和 Y 的值相等")
End If
End Sub
4、嵌套if语句示例
Private Sub nested_if_demo_Click()
Dim a As Integer
a = 12
If a > 0 Then
MsgBox ("The Number is a POSITIVE Number")
If a = 1 Then
MsgBox ("The Number is Neither Prime NOR Composite")
ElseIf a = 2 Then
MsgBox ("The Number is the Only Even Prime Number")
ElseIf a = 3 Then
MsgBox ("The Number is the Least Odd Prime Number")
Else
MsgBox ("The Number is NOT 0,1,2 or 3")
End If
ElseIf a < 0 Then
MsgBox ("The Number is a NEGATIVE Number")
Else
MsgBox ("The Number is ZERO")
End If
End Sub
5、switch语句
Private Sub switch_demo_Click()
Dim MyVar As Integer
MyVar = 1
Select Case MyVar
Case 1
MsgBox "The Number is the Least Composite Number"
Case 2
MsgBox "The Number is the only Even Prime Number"
Case 3
MsgBox "The Number is the Least Odd Prime Number"
Case Else
MsgBox "Unknown Number"
End Select
End Sub