userform上的搜索命令按钮无法正常工作

时间:2015-02-24 00:59:31

标签: excel excel-vba vba

我在userform上有一个搜索按钮。我想要做三件事。如果用户选择“搜索”按钮而不在TextBox6中放置任何文本,我想要弹出一个msgbox并告诉他们需要添加客户代码。如果他们输入的客户代码不在Excel电子表格中并选择“搜索”按钮,我希望弹出一个msgbox并告诉他们客户代码不存在。当他们选择OK时,我希望TextBox6清除,光标在TextBox6上设置焦点。如果他们在Excel电子表格中的TextBox6中输入代码并选择“搜索”按钮,我希望该记录填充用户表单。我使用下面的代码,它适用于上面的场景1和2。但是当excel电子表格中存在代码时,在填充userform之后,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

1 个答案:

答案 0 :(得分: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