我有一些VBA代码,将日期过滤器应用于数据集以进行进一步的工作。当前,日期过滤器是根据预定义条件应用的:
Worksheets("PSE Data").Activate
StartDate = DateSerial(Year(Date), Month(Date), Day(Date))
EndDate = DateSerial(Year(Date), Month(Date) + 3, Day(Date))
ActiveSheet.ListObjects("PSE_Data").Range.AutoFilter Field:=17, _
Criteria1:=">=" & StartDate, _
Operator:=xlAnd, _
Criteria2:="<=" & EndDate
ActiveSheet.ListObjects("PSE_Data").Range.AutoFilter Field:=6, _
Criteria1:="M"
With ActiveSheet.ListObjects("PSE_Data").Sort
.SortFields.Add Key:= _
Range("PSE_Data" & "[Sugg Start Date]"), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
.Apply
End With
我想做的是用弹出框中的用户输入值替换StartDate和EndDate。你能帮忙吗?
答案 0 :(得分:0)
Dim StartDate, EndDate As Date
StartDate = InputBox("Enter start date: ")
EndDate = InputBox("Enter end date: ")
答案 1 :(得分:0)
这是一种典型的方式:
Sub dural()
Dim StartDate As Date, EndDate As Date
With Application
StartDate = CDate(.InputBox(Prompt:="enter startdate mm/dd/yyyy", Type:=2))
EndDate = CDate(.InputBox(Prompt:="enter enddate mm/dd/yyyy", Type:=2))
MsgBox StartDate & vbCrLf & EndDate
End With
End Sub
答案 2 :(得分:0)
这是一个使用函数获取和验证用户输入的示例。它使用Application.InputBox
提示用户输入,然后使用IsDate
检查有效日期。
Option Explicit
Sub test()
'prompt user for start date
Dim StartDate As Variant
StartDate = GetUserInputDate("start")
If StartDate = False Then Exit Sub 'user cancelled
StartDate = CDate(StartDate)
'prompt user for end date
Dim EndDate As Variant
EndDate = GetUserInputDate("end")
If EndDate = False Then Exit Sub 'user cancelled
EndDate = CDate(EndDate)
ActiveSheet.ListObjects("PSE_Data").Range.AutoFilter Field:=17, _
Criteria1:=">=" & StartDate, _
Operator:=xlAnd, _
Criteria2:="<=" & EndDate
End Sub
Function GetUserInputDate(ByVal promptPart As String) As Variant
Dim temp As Variant
Do
temp = Application.InputBox("Enter " & promptPart & " date (ie. mm/dd/yyyy):", "Date?")
Loop Until (temp = False) Or (IsDate(temp))
GetUserInputDate = temp
End Function