简体   繁体   中英

Userform, how to add date filter range

I wish to use Userform option for date filters, user will enter "start time" & "end time" and all relevant data will be displayed according to this filter.

I used local Macro that use two different cells for data input but file view is bad and this is the reason I want to use Useform option.

My code:

Public Sub MyFilter()
    Dim lngStart As Date, lngEnd As Date
    lngStart = Range("b2").Value 'assume this is the start date
    lngEnd = Range("b3").Value 'assume this is the end date
    Range("q:q").AutoFilter Field:=1, _
        Criteria1:=">=" & lngStart, _
        Operator:=xlAnd, _
        Criteria2:="<=" & lngEnd


           Range("A1:s3000").Select
    Range("A:A").Activate
    Selection.Copy
    Sheets.Add After:=ActiveSheet
With ActiveSheet
    .Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
    .Columns("A:A").EntireColumn.AutoFit
    .Cells.Select
    .Cells.EntireColumn.AutoFit
    .Rows("1:1").Select
    .Application.CutCopyMode = False
    With Selection
         With .Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .Color = 15773696
            .TintAndShade = 0
            .PatternTintAndShade = 0
        End With
        .AutoFilter
           Columns("Q:Q").Select
    Selection.NumberFormat = "[$-409]m/d/yy h:mm AM/PM;@"
    End With
    .Columns("A:A").EntireColumn.AutoFit
    .Range("A2").Select
End With

End Sub

The code also copy the data to a new sheet ( any idea how to copy it to a new file?) and changed some cells format.

Thanks!!

For copying paste buffer to a new file, add a new file (instead of a sheet):

Set fNew = = Workbooks.Add(xlWBATWorksheet)
 ...
fNew.SaveAs Filename:=<file specification>

Paste:=xlPasteValues literally copies values without any formatting, comments, borders, etc. For keeping source format, simply use ActiveSheet.Paste Destination:=Range("A1") . If - for any reason - it does not work, you can try this:

.Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
.Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

For copying only the filtered rows, use this:

Range("A1:S3000").SpecialCells(xlCellTypeVisible).Copy
fNew.Sheets(1).Range("A1").PasteSpecial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM