2015-02-24 61 views
0

我在用戶窗體上有一個搜索按鈕。我想要3件事情發生。如果用戶選擇搜索按鈕而不在TextBox6中放置任何文本,我想要一個msgbox彈出並告訴他們他們需要添加客戶代碼。如果他們輸入的客戶代碼不在Excel電子表格中並選擇搜索按鈕,我想要一個msgbox彈出並告訴他們客戶代碼不存在。當他們選擇OK時,我希望TextBox6清除,並且光標在TextBox6上設置焦點。如果他們在Excel電子表格中的TextBox6中輸入代碼並選擇搜索按鈕,我希望該記錄填充用戶窗體。我使用下面的代碼,它適用於上面的場景1和2。但是,當代碼存在於Excel電子表格中時,在填充用戶表單之後,說客戶代碼不存在的msgbox仍然彈出。你能調整我的代碼,這樣不會發生?用戶表單上的搜索命令按鈕無法正常工作

Private Sub CommandButton2_Click() 
Dim ws As Worksheet 
Dim strSearch As String 
Dim aCell As Range 

On Error GoTo Err 

    'validate text box 
If TextBox6.Value = "" Then 
    MsgBox "Please Enter Customer Code" 
    Cancel = True 
    Me.TextBox6.SetFocus 

    Else 
row_number = 0 

Do 
DoEvents 

row_number = row_number + 1 

items_in_review = Sheets("sheet1").Range("A" & row_number) 

If items_in_review = TextBox6.Text Then 
    TextBox1.Text = Sheets("sheet1").Range("B" & row_number) 
    TextBox2.Text = Sheets("sheet1").Range("C" & row_number) 
    TextBox3.Text = Sheets("sheet1").Range("D" & row_number) 
    TextBox4.Text = Sheets("sheet1").Range("F" & row_number) 
    TextBox5.Text = Sheets("sheet1").Range("H" & row_number) 
    TextBox7.Text = Sheets("sheet1").Range("I" & row_number) 
    TextBox8.Text = Sheets("sheet1").Range("G" & row_number) 

Me.TextBox7.Visible = True 
Me.Label8.Visible = True 

End If 
Loop Until items_in_review = "" 

    MsgBox "Customer Code not Found" 
     Cancel = True 
    UserForm1.TextBox6.Value = "" 
    TextBox6.SetFocus 

Exit Sub 

Err: 
MsgBox Err.Description 
End If 
End Sub 

回答

0

我寧願不清除搜索框,如果自己是不是發現:因爲這很煩人,如果你要重新輸入,只是因爲你犯了一個錯字整件事用戶...

Private Sub CommandButton2_Click() 
Dim ws As Worksheet 
Dim strSearch As String 
Dim aCell As Range, v 

On Error GoTo Err 

'validate text box 
v = Trim(TextBox6.Value) 
If Len(v) = 0 Then 
    MsgBox "Please Enter Customer Code" 
    Cancel = True 
    Me.TextBox6.SetFocus 
    Exit Sub 
End if 

Set aCell = Sheets("sheet1").Range("A:A").Find(v, lookat:=xlWhole) 

if not aCell is Nothing Then 

    with aCell.EntireRow 

     TextBox1.Text = .Cells(,"B").Value 
     TextBox2.Text = .Cells(,"C").Value 
     TextBox3.Text = .Cells(,"D").Value 
     TextBox4.Text = .Cells(,"F").Value 
     TextBox5.Text = .Cells(,"H").Value 
     TextBox7.Text = .Cells(,"I").Value 
     TextBox8.Text = .Cells(,"G").Value 

    end with 

    Me.TextBox7.Visible = True 
    Me.Label8.Visible = True 

else 
    MsgBox "Customer Code not Found" 
    Cancel = True 
    'UserForm1.TextBox6.Value = "" 'don't do this! 
    TextBox6.SetFocus 
end if 

Exit Sub 

Err: 
    MsgBox Err.Description 

End Sub 
+0

添...感謝你的幫助......完美的作品。感謝您關於不清除搜索框的建議。 – Jeff 2015-02-24 03:52:13