做循环不循环

时间:2015-03-25 03:38:51

标签: vba excel-vba excel-2003 excel

我在Userform

中有这个循环代码
Private Sub cmdLogin_Click()
Dim user, pass As String
Dim x As Integer

user = Me.user1.Text
pass = Me.pass1.Text

x = 2
Do While ActiveWorkbook.Worksheets("Sheet1").Cells(x, 1).Value <> ""
    If ActiveWorkbook.Worksheets("Sheet1").Cells(x, 1).Value = user _
    And ActiveWorkbook.Worksheets("Sheet1").Cells(x, 2).Value = pass Then
       MsgBox "YES"
       Exit Do
    Else
       MsgBox "NO"
       Exit Do
    End If
Loop
End Sub

但似乎代码不会在整个单元格中循环,只会在x = 2或单元格(2,1)之前停止。这导致无法通过整个用户名和密码列表,每个用户名和传递i输入都会出错,除了第2行的那些。请帮助,因为我是VBA的新手

3 个答案:

答案 0 :(得分:4)

如果Cells(2,1)不是"",那么您有一个无限循环,因为您永远不会增加x

Loop之前添加:x = x + 1来增加循环次数。

我建议您使用these examples中的一些来了解VBA循环的工作原理。

答案 1 :(得分:1)

@PortlandRunner我找到了答案。谢谢你的帮助。而不是在循环之前放置x = x + 1我做了这个

Do While ActiveWorkbook.Worksheets("Sheet1").Cells(x, 1).Value <> ""

    If ActiveWorkbook.Worksheets("Sheet1").Cells(x, 1).Value = user And ActiveWorkbook.Worksheets("Sheet1").Cells(x, 2).Value = pass Then
       MsgBox "YES"
       Exit Do
    Else
        x = x + 1
       If ActiveWorkbook.Worksheets("Sheet1").Cells(x, 1).Value = user And ActiveWorkbook.Worksheets("Sheet1").Cells(x, 2).Value = pass Then
        MsgBox "YES"
       Exit Do
       Else
        MsgBox "NO"
        Exit Do
       End If
    End If
loop

非常感谢帮助过的人们。)

答案 2 :(得分:0)

为了简化你自己的答案Angelo,这里有一些提示:

With ActiveWorkbook.Worksheets("Sheet1")
    If (.Cells(x, 1) = user And .Cells(x, 2) = pass) Or _
    (.Cells(x + 1, 1) = user And .Cells(x + 1, 2) = pass) Then
        MsgBox "YES"
        Exit Do
    Else
        MsgBox "NO"
    End If
End With