如果FIND无法找到输入VBA6

时间:2015-06-27 09:02:07

标签: excel-vba vba excel

它刚刚告诉我如果用户放入不在数据库中的东西(excel电子表格)怎么办?我已经倾倒了所有这些已发布的修补程序,似乎没有一个能满足我的需求。有人会查看我的代码吗。

Private Sub OkayCommandButton_Click()
Worksheets("Parts List").Select
Application.ScreenUpdating = False
Range("A2").Select
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
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)

Range.Find的规范是,如果搜索区域中没有搜索词,则返回NothingNothing是您可以测试的特殊值。

要处理不存在的搜索字词,请尝试在Dim rFindResult As Range行后立即添加Private Sub...,然后更改Cells.Find语句,如下所示:

Set rFindResult = Cells.Find(What:=KN, After:=Range("A1"), LookIn:=xlFormulas, _
      LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
      MatchCase:=False, SearchFormat:=False)

If (rFindResult Is Nothing) Then
    ` display MesgBox, reset focus appropriately, exit sub
Else
    rFindResult.Activate
End If
Siddarth Rout关于指定使用哪张纸而不是隐含地依赖活动纸张的观点非常值得注意。此外,如果未指定部件编号和看板编号,则在将焦点设置为部件编号后可能应该有Exit Sub