循环vba中的多个if语句

leo*_*ill 0 excel vba

我正在尝试运行一个简单的 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
Run Code Online (Sandbox Code Playgroud)

Ste*_*eES 5

在 VBA 中有几种写If语句的方法:

If [some condition] Then [Do something]
Run Code Online (Sandbox Code Playgroud)

或者

If [some condition] Then [Do something] Else [Do something else]
Run Code Online (Sandbox Code Playgroud)

或者

If [some condition] Then
   [Do something]
End If
Run Code Online (Sandbox Code Playgroud)

或者

If [some condition] Then
   [Do something]
Else
   [Do something else]
End If
Run Code Online (Sandbox Code Playgroud)

或者,最后

If [some condition] Then
   [Do something]
ElseIf [some other condition] Then
   [Do something different]
Else
   [Do something else]
End If
Run Code Online (Sandbox Code Playgroud)

在您的代码中,您的If语句都在一行上,因此不需要相应的End If,但也不能Else在下一行中使用相应的语句。如果要使用 anElse或 an ElseIf,则必须使用 finalIf语句块模式并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
Run Code Online (Sandbox Code Playgroud)

  • @leonHill - 你真的应该在一个新问题中提出进一步的问题。 (2认同)