两个TextBox一回答VBA6

时间:2015-06-27 05:10:21

标签: excel-vba vba excel

在我的UserForm中,我有两个文本框。我希望能够通过Text Box查找,但只能使用其中一个。如果两者都是空的,我想要MSGBOX告诉用户输入信息。我可以让我的代码执行/或文本框输入,但不能使用两个文本框,用户跳过TextBox1或不输入任何内容。 这是我的代码.....

Private Sub OkayCommandButton_Click()
Worksheets("Parts List").Select
Application.ScreenUpdating = False
Range("A2").Select
PN = PartNumber.Value
KN = KanbanNumber.Value
If PartNumber = vbNullString Then
   MsgBox "Please enter a Part Number"
   PartNumber.SetFocus
Else
   Cells.find(What:=PN, After:=Range("A2"), LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Activate
End If
If Kanban = vbNullString Then
   MsgBox "Please enter a Kanban Number"
   PartNumber.SetFocus
Else
   Cells.find(What:=KN, After:=Range("A1"), LookIn:=xlFormulas, _
      LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
      MatchCase:=False, SearchFormat:=False).Activate
End If
PartInformation.Caption = _
"Part Number" & vbTab & ActiveCell & vbCrLf & _
"Kanban" & vbTab & vbTab & ActiveCell.Offset(0, 45) & vbCrLf & _
"Part Name" & vbTab & ActiveCell.Offset(0, 1) & vbCrLf & _
"Supplier" & vbTab & vbTab & ActiveCell.Offset(0, 2) & vbCrLf & _
"Next Process" & vbTab & ActiveCell.Offset(0, 3) & vbCrLf & _
"Qty in Tote" & vbTab & ActiveCell.Offset(0, 44) & vbCrLf & _
"PC Location" & vbTab & ActiveCell.Offset(0, 46)
PartInformation1.Caption = "Line    " & ActiveCell.Offset(0, -1)
End Sub

1 个答案:

答案 0 :(得分:2)

您可以先检查两个TextBox-Elements是否为空,然后向用户发送消息。如果该检查失败,则一个或两个Text-Box-Elements都包含文本。你在那里有冲突,因为如果两个文本框都包含搜索字符串,你只想使用一个TextBox-Element进行搜索。在这种情况下,你必须给其中一个文本框优先(你检查的第一个然后获胜):

这只是您的文字片段:

PN = PartNumber.Value
KN = KanbanNumber.Value

If ((PartNumber = vbNullString) And (KanbanNumber = vbNullstring)) Then
   ' Both textboxes are empty, message box opened and focus to part number
   MsgBox "Please enter a Part Number or Kanban Number"
   PartNumber.SetFocus
Else
   ' One or more textboxes contain a search string
    If Not (PartNumber = vbNullString) Then
       'Part number is given, run search
       Cells.find(What:=PN, After:=Range("A2"), LookIn:=xlFormulas, _
            LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False).Activate
    Else
       ' Part Number is not given
       ' Since we checked that at least one textbox contains text
       ' the Kanban Number must be set if Part Number has not been set
       Cells.find(What:=KN, After:=Range("A1"), LookIn:=xlFormulas, _
          LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
          MatchCase:=False, SearchFormat:=False).Activate
    End If
End If