vba elseif不会运行下一个条件

时间:2016-05-15 05:38:43

标签: excel vba userform

我必须创建一个用户表单,代码不会运行下一个条件

If name = "" Then

   MsgBox ("please enter your name")

    End

ElseIf Cleanbox = False And CavBox = False And RayBox = False And FluBox = False And RootBox = False And OtherBox = False Then


    MsgBox ("Please select a service")


    End
ElseIf Cleanbox = True Then

    total = total + 35

ElseIf CavBox = True Then

    total = total + 150

ElseIf RayBox = True Then

    total = total + 85

ElseIf FluBox = True Then

    total = total + 50

ElseIf RootBox = True Then

    total = total + 225

ElseIf OtherBox = True Then

    total = total + other

End If

totaltxt.Value = total

End Sub

total = total + x它不会添加下一个值。
因此,如果raybox为真,则总计将= 85 但如果raybox为真,则为flubox 然后总应该= 135但它仍然是85.

2 个答案:

答案 0 :(得分:2)

你可以简单地遵循以下步骤:

If Name = "" Then
    MsgBox ("please enter your name")

ElseIf Not (Cleanbox Or CavBox Or RayBox Or FluBox Or RootBox Or OtherBox) Then
    MsgBox ("Please select a service")

Else
    totaltxt.Value = -(35 * Cleanbox + 150 * CavBox + 85 * RayBox + 50 * FluBox + 225 * RootBox + othervalue * OtherBox)
End If

此外,我建议您不要使用End声明(谷歌它,你会看到很多原因)并使用适当的If-Then logic代替{ {1}}

答案 1 :(得分:2)

你的逻辑完全错了。在If ... ElseIf ... Else ...块中,只有具有正条件的第一部分将执行如下:

If a = 1 Then
  Debug.Print "a is 1"
ElseIf b = 1 Then
  Debug.Print "b is 1"
End If

如果a不是1,则“b为1”只能弹出。只要想到一个不可见的[all previous conditions are false] And [this condition]

要使您的子项可用,请使用user3598756显示的方式或类似的方式:

  Dim Total As Long

  If Name = "" Then
    MsgBox ("please enter your name")
  Else
    If Cleanbox Then Total = Total + 35
    If CavBox Then Total = Total + 150
    If RayBox Then Total = Total + 85
    If FluBox Then Total = Total + 50
    If RootBox Then Total = Total + 225
    If OtherBox Then Total = Total + other

    If Total > 0 Then
      totaltxt.Value = Total
    Else
      MsgBox ("Please select a service")
    End If
  End If