VBA Refresh UserForm ListBox Data when source changes

我的梦境 提交于 2019-12-06 03:44:07
Prasad

Instead of using var and assigning the data to List from var, you can use Named Range of data in the sheet and assign the property
ListBox1.RowSource = "Name of the Range"

Every time you want to refresh the listbox just use the above assignment in your code and it will work. If you find any difficulty please let me know.

You could add a refresh procedure, then call it in your OnClick event procedure for the button. Note, I haven't tested this code, but it should do what your original question asked.

Private Sub UserForm_Initialize()
    'set ListBox properties on initialization of UserForm
    Set sht = ThisWorkbook.Worksheets("combobox_value")
    lastRow_combobox_column = sht.Cells(sht.Rows.Count, "I").End(xlUp).Row

    With ListBox1
        .ColumnCount = 4
        .ColumnWidths = "100"
        .ColumnHeads = False
        .ControlTipText = True
    End With

    RefreshListbox 
End Sub

Private Sub CommandButton1_Click()    
    Application.EnableEvents = False

    Worksheets("combobox_value").Activate
    Dim strDataRange As Range
    Dim keyRange As Range
    Set strDataRange = Range("I2:L4")
    Set keyRange = Range("I2:I4")

    If Range("M2").Value = "D" Then

        strDataRange.Sort Key1:=keyRange, Order1:=xlDescending
        Range("M2").Value = "A"
    Else
        strDataRange.Sort Key1:=keyRange, Order1:=xlAscending
        Range("M2").Value = "D"
    End If
    Application.EnableEvents = True
    RefreshListbox
End Sub

Private Sub RefreshListbox()
    Me.ListBox1.Clear
    'Load Worksheet Range directly to a ListBox:
    Dim ListRange As Range
    ListRange = Sheets("combobox_value").Range("I2:L" & lastRow_combobox_column)
    Me.ListBox1.List = ListRange
End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!