过滤功能,如果数据不符合条件,提示错误

时间:2019-06-19 07:23:35

标签: excel vba exception

这是更新后的文本框。它只会在值大于0时进行过滤。但是,我似乎无法找出要添加的位置,如果键入了一个值但在过滤器范围内找不到它会提示错误消息

If tbAC.TextLength > 0 Then
    AGCN = Rows("1:1").Find(what:="AGC", lookat:=xlWhole).Column
    ActiveSheet.ListObjects("Table1").Range.AutoFilter field:=AGCN, Criteria1:=tbAC
    'Assuming that I'm supposed to add a line of code here, smth along the line of if criteria:="" 
    'Msgbox "Invalid Input"
ElseIf tbAC.TextLength = 0 Then
    tbAC = ""
End If

成功编辑!

Private Sub tbAC_AfterUpdate()
Dim AGCN As Long
Dim AGCL As String
Dim Namef As Range

AGCN = Rows("1:1").Find(what:="AGC", lookat:=xlWhole).Column
AGCL = Split(Cells(1, AGCN).Address, "$")(1)


If tbAC.TextLength > 0 Then
    'Set Namef = Range(AGCL:AGCL).Find(tbAC)
    Set Namef = Range(AGCL & ":" & AGCL).Find(tbAC)
    If Namef Is Nothing Then
        MsgBox ("Invalid Input")
    Else
        ActiveSheet.ListObjects("Table1").Range.AutoFilter field:=AGCN, Criteria1:=tbAC
    End If
ElseIf tbAC.TextLength = 0 Then
    tbAC = ""
End If

End Sub

1 个答案:

答案 0 :(得分:0)

Variant使用AgentCodeN变量,并像这样使用Application.Match

Option Explicit
Sub test()

    Dim AgentCodeN As Variant

    If tbAC.TextLength > 0 Then
        tbAC = tbAC
        AgentCodeN = Application.Match(Rows("1:1"), "AGC", 0)
        If Not IsError(AgentCodeN) Then
            ActiveSheet.ListObjects("Table1").Range.AutoFilter field:=AGCN, Criteria1:=tbAC
        'Assuming that I'm supposed to add a line of code here, smth along the line of if criteria:=""
        Else
            MsgBox "Invalid Input"
        End If
    ElseIf tbAC.TextLength = 0 Then
        tbAC = ""
    End If

End Sub

我不知道您是否声明了变量,但是使用Option Explicit将迫使您这样做。