1

下面的代码工作正常。但是,当用户未在 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
4

1 回答 1

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 & "*"

代码

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
于 2012-04-20T09:11:00.343 回答