循环vba中的多个if语句

时间:2017-04-05 08:27:48

标签: vba excel-vba excel

我正在尝试运行一个简单的if语句,但是在没有出错的情况下无法让它运行。基本上,我试图在一个循环中有多个if语句,我猜我有一个小错误但无法发现它,可能与else语句。任何帮助表示赞赏

Sub ex13()

Dim rgtimetable As Range, rgR As Range, counter As Integer
Dim counter1 As Integer, counter2 As Integer, counter3 As Integer

Set rgtimetable = Range("timetable")
For Each rgR In rgtimetable
    rgR.Activate
    If classyear(ActiveCell.Value) = 0 Then counter = counter + 1   ' classyear is a function i am calling from above

    Else
    If classyear(ActiveCell.Value) = 1 Then counter = counter1 + 1

    Else
    If classyear(ActiveCell.Value) = 2 Then counter = counter2 + 1

    Else
    If classyear(ActiveCell.Value) = 3 Then counter = counter3 + 1

Next rgR

MsgBox counter
MsgBox counter1
MsgBox counter2
MsgBox counter3

End Sub

1 个答案:

答案 0 :(得分:4)

在VBA中,有几种方法可以编写If语句:

If [some condition] Then [Do something]

或者

If [some condition] Then [Do something] Else [Do something else]

或者

If [some condition] Then
   [Do something]
End If

或者

If [some condition] Then
   [Do something]
Else
   [Do something else]
End If

或者,最后

If [some condition] Then
   [Do something]
ElseIf [some other condition] Then
   [Do something different]
Else
   [Do something else]
End If

在您的代码中,您的If语句都在一行中,因此不需要相应的End If,但也无法获取相应的Else语句在下一行。如果您要使用ElseElseIf,则必须使用最终If语句块模式,并使用相应的If关闭EndIf块。

在你的情况下,因为你总是在测试相同的东西(classyear(ActiveCell.Value)),我建议你利用Select Case构造,这会缩短你的代码。

Select Case classyear(ActiveCell.Value)
Case 0
   counter = counter + 1   ' classyear is a function i am calling from above

Case 1
   counter = counter1 + 1

Case 2
   counter = counter2 + 1

Case 3
   counter = counter3 + 1

Case Else
   'Oops, this shouldn't happen, but handle the error anyway

End Select