VBA输入框过滤器增强功能

时间:2012-04-20 09:04:41

标签: vba excel-vba excel

下面的代码工作正常。但是,当用户未在InputBox中包含任何内容时,点击“关闭”按钮输入一个不存在的值,我希望它显示一个msgbox说明原因并删除工作表'PreTotal'。

有没有更好的方法来处理用户输入?在这里需要一些关于如何去做的帮助。谢谢。

Sub Filterme()
    Dim wSheetStart As Worksheet
    Dim rFilterHeads As Range
    Dim strCriteria As String

    Set wSheetStart = ActiveSheet
    Set rFilterHeads = Range("M1", Range("M1").End(xlToLeft))

    With wSheetStart
        .AutoFilterMode = False

        rFilterHeads.AutoFilter

        strCriteria = InputBox("Enter Date - MMDDYY")

        If strCriteria = vbNullString Then Exit Sub

        rFilterHeads.AutoFilter Field:=13, Criteria1:="=*" & strCriteria & "*"
    End With

    Worksheets("PreTotal").UsedRange.Copy

    Sheets.Add.Name = "Total"

    Worksheets("Total").Range("A1").PasteSpecial

End Sub

1 个答案:

答案 0 :(得分:1)

这是你在尝试的吗?

更改

If strCriteria = vbNullString Then Exit Sub    

If strCriteria = vbNullString Then
    MsgBox "You choose not to continue"
    Application.DisplayAlerts = False
    Worksheets("PreTotal").Delete
    Application.DisplayAlerts = True
    Exit Sub
End If

<强>后续

  
    
      

谢谢@Rout - 这很有用。如果工作表中不存在输入标准,还有一件事情是什么?我应该怎么解决这个问题? - user823911 11分钟前

    
  

这是你在尝试什么?此外,如果您根据 Col M (范围内的第一个Col)过滤范围,则更改行

rFilterHeads.AutoFilter Field:=13, Criteria1:="=*" & strCriteria & "*"

rFilterHeads.AutoFilter Field:=1, Criteria1:="=*" & strCriteria & "*"

<强> CODE

Sub Filterme()
    Dim wSheetStart As Worksheet
    Dim rFilterHeads As Range, aCell As Range
    Dim strCriteria As String

    Set wSheetStart = ActiveSheet
    Set rFilterHeads = Range("M1", Range("M1").End(xlToLeft))

    With wSheetStart
        .AutoFilterMode = False

        strCriteria = InputBox("Enter Date - MMDDYY")

        If strCriteria = vbNullString Then
            MsgBox "You choose not to continue"
            Application.DisplayAlerts = False
            Worksheets("PreTotal").Delete
            Application.DisplayAlerts = True
            Exit Sub
        End If

        Set aCell = .Columns(13).Find(What:=strCriteria, LookIn:=xlValues, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

        If Not aCell Is Nothing Then
            MsgBox "Search Criteria Not Found"
            Exit Sub
        End If

        rFilterHeads.AutoFilter

        rFilterHeads.AutoFilter Field:=13, Criteria1:="=*" & strCriteria & "*"

        Sheets.Add.Name = "Total"
        Worksheets("PreTotal").UsedRange.Copy
        Worksheets("Total").Range("A1").PasteSpecial
    End With
End Sub