应用AutoFilter并在UserForm ListBox中显示结果?

时间:2013-09-04 22:02:15

标签: excel vba excel-vba excel-2007

现在我有一个看起来像这样的UserForm:

enter image description here

我有一个如下所示的电子表格:

enter image description here

我在UserForm_Initialize事件中使用以下代码将AutoFilter应用于我的数据。我需要在列表框中显示AutoFilter的结果,该结果名为“boxPolicyList”。

Worksheets("defaults").Select

Me.boxDateBegin.Value = ActiveSheet.Range("E4").Value
Me.boxDateEnd.Value = ActiveSheet.Range("F4").Value

Workbooks.Open Filename:="Z:\Stuff\production\production_database.xlsm"
Worksheets("policies").Select

    With ActiveSheet
        .AutoFilterMode = False
            With .Range("A1:F1")
                 .AutoFilter
                 .AutoFilter field:=1, Criteria1:=">=" & Me.boxDateBegin.Value, _
                 Operator:=xlAnd, Criteria2:="<=" & Me.boxDateEnd.Value
                 .AutoFilter field:=3, Criteria1:="Bear River Mutual"
            End With
    End With

    Me.txtTotalPolicies.Caption = ActiveSheet.Range("J1").Value
    Me.txtTotalPremium.Caption = ActiveSheet.Range("H1").Value
    Me.txtTotalPremium.Caption = Format(Me.txtTotalPremium.Caption, "$#,###,###.00")

Workbooks("production_database.xlsm").Activate
ActiveWorkbook.Save
ActiveWorkbook.Close

有谁知道如何做到这一点?

1 个答案:

答案 0 :(得分:0)

...也许

Private Sub UserForm_Initialize()

    Dim rngVis As Range

    Me.boxDateBegin.Value = Sheets("defaults").Range("E4").Value
    Me.boxDateEnd.Value = Sheets("defaults").Range("F4").Value

    With Workbooks.Open("Z:\Stuff\production\production_database.xlsm")
        With Sheets("policies")
            .AutoFilterMode = False

            Me.txtTotalPolicies.Caption = .Range("J1").Value
            Me.txtTotalPremium.Caption = Format(.Range("H1").Value, "$#,###,###.00")

            With Intersect(.UsedRange, .Range("A:F"))
                .Sort Intersect(.Cells, .Parent.Columns("C")), xlAscending, Intersect(.Cells, .Parent.Columns("A")), , xlAscending, Header:=xlGuess
                .AutoFilter 3, "Bear RIver Mutual"
                .AutoFilter 1, ">=" & Me.boxDateBegin.Value, xlAnd, "<=" & Me.boxDateEnd.Value
                On Error Resume Next
                Set rngVis = .Offset(1).Resize(.Rows.Count).SpecialCells(xlCellTypeVisible)
                On Error GoTo 0
                If Not rngVis Is Nothing Then Me.boxPolicyList.List = rngVis.Value
            End With
        End With
        .Close False
    End With

End Sub