If there is no value in a filter then exit sub

2019-08-12 22:41发布

I am running a macro where it filters based on a number that the user has entered. It then takes that number and filters a list based on that value. I need a validation where if a user put in a number that is not on the list it will exit the macro. I think I am close but I am new to VBA so I keep getting stuck. Any help would be awesome!

Thanks!

    'Filter based on user entry
Sheets("New Revision ").Select
    part = Range("B4").Value
    Sheets("PN_List").Select
    Columns("D:E").Select
    Selection.EntireColumn.Hidden = False
    ActiveSheet.Range("$A$1:$K$3000").AutoFilter Field:=1, Criteria1:=part
    If ActiveSheet.Range("$A$1:$K$3000").AutoFilter Field=1, Criteria1="" Then
    MsgBox "Part number not found please try again.", vbOKOnly + vbExclamation, "Entry Error"
    Exit Sub
    End If

2条回答
别忘想泡老子
2楼-- · 2019-08-12 23:17

Try this out:

Sub Parts()
Dim Part As Variant
Dim Found As Boolean
  Part = Sheets("New Revision").Range("B4").Value
  On Error Resume Next ' If the lookup fails, ignore the error
    ' the following assumes Part is in Column A
    Found = WorksheetFunction.Match(Part, Sheets("PN_List").Range("$A$1:$A$3000"), 0) > 0
  On Error GoTo 0 ' Resume normal error handling
  If Not Found Then
    MsgBox "Part number not found please try again.", vbOKOnly + vbExclamation, "Entry Error"
  End If
End Sub

Edit: you can still filter if you want that. Maybe a good place to do that is in an Else clause of If Not Found.

查看更多
Juvenile、少年°
3楼-- · 2019-08-12 23:26
Sheets("New Revision ").Select
    part = Range("B4").Value
    Sheets("PN_List").Select
    If Application.Countif([A1:A3000], part)  < 1 Then
    MsgBox "Part number not found please try again.", vbOKOnly + vbExclamation, "Entry Error"
    Exit Sub
    End If
    Sheets("PN_List").Columns("D:E").EntireColumn.Hidden = False
    ActiveSheet.Range("$A$1:$K$3000").AutoFilter Field:=1, Criteria1:=part
查看更多
登录 后发表回答