尽管使用了 End If 语句,但仍出现错误“Block If without End If”

尽管使用了 End If 语句,但仍出现错误“Block If without End If”

我有一个组合框,Word它应该termShorthand根据数组中的选择填充文本字段termWritten。我收到了不带 End If 的 If 块尽管我在 If 语句之后出现了编译错误,但仍然出现该错误。

Private Sub termWritten_DropButtonClick()
    termWritten.List = Array("first", "second", "third", "final")
End Sub

Private Sub termWritten_Change()
    If termWritten.Value = "first" Then
        termShorthand.Value = "three (3)"
    Else
        If termWritten.Value = "second" Then
            termShorthand.Value = "two (2)"
        Else
            If termWritten.Value = "third" Then
                termShorthand.Value = "one (1)"
            Else
                If termWritten.Value = "final" Then
                    termShorthand.Value = "no"
                End If
End Sub

答案1

您需要一份End If声明每个 If语句,如下所示:

Private Sub termWritten_Change()
    If termWritten.Value = "first" Then
        termShorthand.Value = "three (3)"
    Else
        If termWritten.Value = "second" Then
            termShorthand.Value = "two (2)"
        Else
            If termWritten.Value = "third" Then
                termShorthand.Value = "one (1)"
            Else
                If termWritten.Value = "final" Then
                    termShorthand.Value = "no"
                End If 'final
            End If 'third
        End If 'second
    End If 'first
End Sub

您可以详细了解如果...那么...否则声明微软文档

答案2

@twisty impersonator 关于 if/then/else 语法的说法是正确的,但是如果您使用 Select Case,您的代码会更容易理解和更新:

Private Sub termWritten_Change()

Select Case termWritten.Value
   Case Is = "first
      termShorthand.Value = "three (3)"
   Case Is = "second"
      termShorthand.Value = "two (2)"
   ' and so on, adding another Case Is = "xyz" for each value
   ' you want to test for.  At the end, it's usually a good idea to
   ' include
   Case Else
     ' This runs if no other conditions are met
     ' Use it to set an error code, supply a default value, etc.
End Select

End Sub

按照 twisty 的示例,我添加了指向 MS 的 Select Case 文档的链接:

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/select-case-statement

答案3

虽然Select Case可能更好,但值得一提的是,您可以使用ElseIf,然后只End If需要一个

Private Sub termWritten_DropButtonClick()

   termWritten.List = Array("first", "second", "third", "final")

End Sub

Private Sub termWritten_Change()

   If termWritten.Value = "first" Then

       termShorthand.Value = "three (3)"

   ElseIf termWritten.Value = "second" Then

       termShorthand.Value = "two (2)"

   ElseIf termWritten.Value = "third" Then

       termShorthand.Value = "one (1)"

   ElseIf termWritten.Value = "final" Then

       termShorthand.Value = "no"

   End If

子目录结束

相关内容