Expected Statement End If

两盒软妹~` 提交于 2020-04-17 14:22:43

问题


I have the following code setup in a form and I'm getting the "Expected Statement" error. My first time doing this and thought I had the syntax correct, what am I missing?

            <%
            If Trim(oQuote("shipmeth"))="FREIGHT" Then 
                Response.Write "Freight" 
            ElseIf Trim(oQuote("shipmeth"))="THRSHLD" Then 
                Response.Write "Threshold"
            End If
            %>

回答1:


When using nested 2-way conditionals, each conditional must be closed by its own End If:

If condition_A Then
  action_A
Else
  If condition_B Then
    action_B
  Else
    If condition_C Then
      action_C
    Else
      action_D
    End If 'condition_C
  End If 'condition_B
End If 'condition_A

Only an n-way conditional can be closed with a single End If (because it's just a single conditional):

If condition_A Then
  action_A
ElseIf condition_B Then
  action_B
ElseIf condition_C Then
  action_C
Else
  action_D
End If

However, this kind of n-way conditional only makes sense when you're checking different conditions, e.g.

If IsEmpty(a) Then
  ...
ElseIf b > 23 Then
  ...

When checking the same variable for different values it's better to use a Select statement as Alex K. suggested:

Select Case foo
  Case "a"
    'handle foo="a"
  Case "b", "d"
    'handle foo="b" as well as foo="d"
  Case Else
    'handle non-matches
End Select



回答2:


The first statement following the If must be on a new line;

If Trim(oQuote("shipmeth"))="FREIGHT" Then 
  Response.Write "Freight" 

Following conditions can be on the same line but must use ElseIf

ElseIf Trim(oQuote("shipmeth"))="THRSHLD" Then Response.Write "Threshold"
ElseIf ...

I would suggest a more readable Case;

select case Trim(oQuote("shipmeth"))
    Case "THRSHLD"
        Response.Write "Threshold"
    Case "PREMTHRHLD"
        Response.Write "Premium Threshold"
    ...
end select

Which has the additional advantage of only ever executing Trim(oQuote("shipmeth")) once.




回答3:


I think "else if" should be one word, like elseif




回答4:


You have nice answers here, I'll append just one more (lightly optimized) alternative.

strTest   = Trim(oQuote("shipmeth"))
strResult = "Unexpected"
If strTest ="FREIGHT" Then strResult = "Freight"
If strTest ="THRSHLD" Then strResult = "Threshold"
Response.Write strResult

EDIT

And just to clarify my thought, I hate nested If..Then, unfortunately no GoTo Label in VBScript, therefore above double comparison could be optimized with function.

strResult = "Unexpected"
MyResponse Trim(...), strResult
Response.Write strResult

Sub MyResponse(strIn, strOut)
    If strIn = "FREIGHT" Then
        strOut = "Freight" : Exit Sub
    End If
    If strIn = "THRSHLD" Then strOut = "Threshold"
End Sub


来源:https://stackoverflow.com/questions/16940517/expected-statement-end-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!