Apply AutoFilter and display results in UserForm ListBox?

半世苍凉 提交于 2019-12-25 05:13:08

问题


Right now I have a UserForm that looks like this:

I have a spreadsheet that looks like this:

I am using the following code in the UserForm_Initialize event to apply an AutoFilter to my data. I need to display the results of the AutoFilter in my listbox which is named "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

Does anyone know how this can be done?


回答1:


Perhaps...

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


来源:https://stackoverflow.com/questions/18624550/apply-autofilter-and-display-results-in-userform-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!