2015-03-25 154 views
1

我有這個循環代碼在我的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)。此結果不能通過用戶名和密碼的整個列表和每個用戶名和通行證我輸入變得除了在第2行的錯誤。請幫助,因爲我是新的VBA

+0

@PortlandRunner後它的答案,我會刪除我的:) – L42 2015-03-25 03:50:58

+0

感謝@ L42我欣賞的報價 – 2015-03-25 03:52:43

+0

@PortlandRunner主席先生,我沒有地方X = X + 1,但它仍然無法讀取正確的用戶名和密碼。這次只有第3行正在確定。 – 2015-03-25 04:14:32

回答

4

如果Cells(2,1)不是""那麼你有一個無限循環,因爲你永遠不會增加x

Loop之前加上:x = x + 1來增加你的循環。

我建議你玩一些these examples來了解VBA循環是如何工作的。

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 

非常感謝你給誰幫助:)

0

只是爲了簡化你自己的答案安傑洛的人,這裏有一些提示:

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