VBA Excel-根据用户输入使用xlFilterAllDatesInPeriod“月”

时间:2018-09-14 04:27:36

标签: excel vba

我有一个简单的用户窗体,该窗体使用ComboBox列出了一年中的所有月份。有一个“关闭”按钮和一个“运行”按钮。单击“运行”按钮后,我希望使用“ xlFilterAllDatesInPeriod-month”条件过滤活动工作表中的列,并且用户应从ComboBox中选择月份。

'List of months
Private Sub UserForm_Initialize()
     With ComboBox1
       .AddItem "January"
       .AddItem "February"
       .AddItem "March"
       .AddItem "April"
       .AddItem "May"
       .AddItem "June"
       .AddItem "July"
       .AddItem "August"
       .AddItem "September"
       .AddItem "October"
       .AddItem "November"
       .AddItem "December"
    End With
End Sub

'Close button
Private Sub CommandButton2_Click() 
   Unload Me
End Sub

'Run the code button
Private Sub CommandButton1_Click()
   If ComboBox1.Value = "" Then
       MsgBox "Please choose a month"
   Else
       Sheets("MASTER LIST").Select
       ActiveSheet.Range("$A$2:$T$289").AutoFilter Field:=15, Criteria1:= _
           xlFilterAllDatesInPeriod"Month", Operator:=xlFilterDynamic
       Unload Me
   End If
End Sub

这些是我现在拥有的代码。 Criteria1上的“月”部分应基于用户输入。请提供有关如何使它工作的建议。

感谢您的帮助,并预先感谢!

1 个答案:

答案 0 :(得分:0)

使用Select Case将组合框选择转换为相关的枚举常量。

Private Sub CommandButton1_Click()
   dim xlMonth as long

   xlMonth = 0
   select case ComboBox1.value
       case "January"
           xlmonth = xlFilterAllDatesInPeriodJanuary
       case "February"
           xlmonth = xlFilterAllDatesInPeriodFebruary
       case "March"
           xlmonth = xlFilterAllDatesInPeriodMarch
       case "April"
           xlmonth = xlFilterAllDatesInPeriodApril
       case "May"
           xlmonth = xlFilterAllDatesInPeriodMay
       case "June"
           xlmonth = xlFilterAllDatesInPeriodJune
       case "July"
           xlmonth = xlFilterAllDatesInPeriodJuly
       case "August"
           xlmonth = xlFilterAllDatesInPeriodAugust
       case "September"
           xlmonth = xlFilterAllDatesInPeriodSeptember
       case "October"
           xlmonth = xlFilterAllDatesInPeriodOctober
       case "November"
           xlmonth = xlFilterAllDatesInPeriodNovember
       case "December"
           xlmonth = xlFilterAllDatesInPeriodDecember
       case else
           MsgBox "Please choose a month"
    end select

    if cbool(xlmonth) then
       with workSheets("MASTER LIST")
           .Select
           .Range("$A$2:$T$289").AutoFilter Field:=15, _
               Criteria1:=xlmonth , Operator:=xlFilterDynamic
       end with
       Unload Me
    End If

End Sub