我收到语法错误,可以请检查我的代码吗?

时间:2018-11-28 03:02:54

标签: excel vba

请检查代码,我认为错误在于退出错误循环。

Option Explicit
Dim mm
Dim person As Range
Dim amount As Range
Dim ans

Sub Macro1()

again:
mm = InputBox("Enter the name of the sales person")
If mm = "Jack" Then
    GoTo Start
ElseIf mm = "Heather" Then
    GoTo Start
ElseIf mm = "Jeff" Then
    GoTo Start
ElseIf mm = "Stephanie" Then
    GoTo Start
ElseIf mm = "Mike" Then
    GoTo Start
ElseIf mm = "Marty" Then
    GoTo Start
ElseIf mm = "Peter" Then
    GoTo Start
ElseIf mm = "Jack" Then
    GoTo Start
ElseIf mm = "Lisa" Then
    GoTo Start
Else
GoTo Error
Error:
MsgBox ("Error: invalid name,no match found")
ans = MsgBox("Do you want to try again?", vbYesNo)
If ans = 8 Then
GoTo again
ElseIf ans = 7 Then
GoTo Exit

Start:
    Set person = Range(Cells(6, 2), Cells(148, 2))
    Set amount = Range(Cells(6, 3), Cells(148, 3))
    Cells(13, 8) = mm
    Cells(14, 8) = WorksheetFunction.SumIfs(amount, person, mm)
    Cells(15, 8) = WorksheetFunction.AverageIfs(amount, person, mm)
    Cells(16, 8) = WorksheetFunction.MinIfs(amount, person, mm)
    Cells(17, 8) = WorksheetFunction.MaxIfs(amount, person, mm)
    ans = MsgBox("Do you want to try again?", vbYesNo)
If ans = 8 Then GoTo again
    End If
Exit:
End Sub

出于某些奇怪的原因,excel不允许我输入Exit:它显示了编译错误,但我不知道为什么

非常感谢您的帮助

2 个答案:

答案 0 :(得分:3)

Exit是保留关键字,对于标识符无效。

Exit:
End Sub

Exit标签需要重命名。

答案 1 :(得分:3)

这就是我重新构造代码的方法。请注意,由于GoTo的实例,代码并未从此处跳到那里。现在,您可以从头到尾遵循逻辑,而无需跳过一行。这大大提高了可读性,有助于进行调试,将来进行修改以及首先编写脚本。

如果您想提供一个选项,可以尝试使用名称,直到碰巧输入您的操作名称之一,则可以添加Do Loop。您应该查找该方法,如果决定实施并遇到任何问题,请在代码和问题中发布一个新问题!

以下是该主题上的一些随机链接,这些链接应有助于您入门。 Herehere


Sub Test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1") '<-- Update sheet name
Dim mm As String, Person As Range, Amount As Range

Set Person = ws.Range("B6:B148")
Set Amount = ws.Range("C6:C148")

mm = InputBox("Enter the name of the sales person")

Select Case mm
    Case "Jack", "Heather", "Jeff", "Mike", "Marty", "Peter", "Jack", "Lisa"
        ws.Range("H13") = mm
        ws.Range("H14") = Application.WorksheetFunction.SumIfs(Amount, Person, mm)
        ws.Range("H15") = Application.WorksheetFunction.AverageIfs(Amount, Person, mm)
        ws.Range("H16") = Application.WorksheetFunction.Minifs(Amount, Person, mm)
        ws.Range("H17") = Application.WorksheetFunction.Maxifs(Amount, Person, mm)
    Case Else
        MsgBox "Invalid Entry. Please re-run macro to try again"

End Select

End Sub
相关问题