⚫ if语句是VBA经常用到的判断结构。其有三种形式。 ▶iif函数,和工作表的if函数一样。下面是一个简单的自定义函数。如果a的值大于0,则ta=999,否则ta=666。 Function ta(a As Integer) As Integer
ta = IIf(a > 0, 999, 666) ▶单行的if语句。将上面的例子改为单行的if语句如下。 Function ta(a As Integer) As Integer ▶ if 结构,将上面例子改为 if结构写法。 Function ta(a As Integer) As Integer ▶如果要执行一个以上的操作,可以使用if结构,下拉if结构,判断x和y的大小,如果x大于y,那么x 10,y-10。 Sub iiiif()
Dim x%, y% ▶上述例子,假如,不单单x>y要进行操作,x<=y也要进行操作,可以如下写:如果x>y,则x 10,y-10;否则x-10,y 10 Sub iiiif()
Dim x%, y%
x = 5
y = 3
If x > y Then
x = x 10
y = y - 10
Else
x = x - 10
y = y 10
End If
End Sub ▶如果x,y要分开判断x>y,x<y,x=y三种情况,if语句可以这样写,如果x>y,x 10,y-10,如果x<y,x-10,y 10,其他是(x=y)x 1,y-1。 Sub iiiif()
Dim x%, y%
x = 5
y = 3
If x > y Then
x = x 10
y = y - 10
ElseIf x < y Then
x = x - 10
y = y 10
Else
x = x 1
y = y - 1
End If
End Sub ▶当判断条件较多的时候,if结构里可以有多个elseif语句。if结构里的判断语句,一旦条件成立,代码立即执行操作,然后结束if结构(end if)。 ▶如上面的代码,x=5,y=3,先判断x>y,条件成立,执行x 10,y-10操作,结束if(代码直接调到end if);如果x>y不成立,那么执行判断x<y,成立的话,则执行x-10,y 10操作,代码跳转到end if,结束判断...... ⚫正如For循环可以嵌套For循环,if结构里面也可以包含另外一个或多个if结构,视乎实际情况而定。百度一个栗子,如下,着背景绿色的是一个完整的if结构,观察其结构,可以明显知道 if开头end if结束。 Private Sub nested_if_demo_Click()
Dim a As Integer
a = 23
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 下面,来一个老掉牙的栗子,判断等级(代码不解释了) Sub Cat()
Dim i% |
|
来自: L罗乐 > 《VBA基础入门教程》