我无法比较用户输入和曲棍球运动员列表

时间:2017-04-25 20:42:18

标签: excel vba excel-vba

Picture of Code

Private Sub NextR_Click()
    Dim a As Integer
    If Goalie1.Value = "" Or Goalie2.Value = "" Then
        MsgBox "Please make sure that you have a goalie entered for both teams and that the name is spelled correctly."
    Else
        For a = 3 To 500
            If Goalie1.Value = Sheets("Players").Cells(a, 9) Then
                Sheets("Game").Range("C5").Value = Cells(a, 6)
                Sheets("Game").Range("D5").Value = Cells(a, 7)
                Sheets("Game").Range("E5").Value = Cells(a, 8)
            Else
                Sheets("Game").Range("C5").Value = 5
            End If
        Next a
        For a = 3 To 500
            If Sheets("Players").Cells(a, 9).Value = Goalie2.Value Then
                Sheets("Game").Range("I5").Value = Cells(a, 6)
                Sheets("Game").Range("J5").Value = Cells(a, 7)
                Sheets("Game").Range("K5").Value = Cells(a, 8)
            Else
                Sheets("Game").Range("I5").Value = 10
            End If
        Next a

    End If
End Sub

我有2张,一张列为“游戏”,另一张列为“玩家”。 “球员”表中有一系列曲棍球守门员和球员,他们的球员有玩游戏,投篮和位置的统计数据,守门员有射门,射门得分。我让用户在用户表单输入框中输入守门员名称,并将其与守门员列表中的所有名称进行比较。出于某种原因,该程序仍然将我的守门员名称设置为5和10.你能帮我理解为什么会这样吗。

1 个答案:

答案 0 :(得分:0)

无论您是否找到守门员匹配,您所拥有的代码都会在第3到第500行中运行。当你找到合适的守门员时,它并没有停止。

找到正确的行后,您需要退出For循环。使用Exit For statement,如下所示:

For a = 3 To 500
    If Goalie1.Value = Sheets("Players").Cells(a, 9) Then
        Sheets("Game").Range("C5").Value = Cells(a, 6)
        Sheets("Game").Range("D5").Value = Cells(a, 7)
        Sheets("Game").Range("E5").Value = Cells(a, 8)
        Exit For
    Else
        Sheets("Game").Range("C5").Value = 5
    End If
Next a