我想在表格中過濾結果並用此結果創建列表框, 此代碼適用於表單上的列表框,但不適用於表單,任何想法?創建帶有過濾值的列表框excel
Sub MyListBox()
Dim rng As Range
Dim vArr As Variant
Dim ListBox1 As Object ---> this works on sheet but not works on form
Dim x As Single
Dim y As String
y = Worksheets("Sheet2").Cells(1, 12).Value
x = Worksheets("Sheet2").Cells(2, 12).Value
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Set rng = Range("TestMaterial")
Set ListBox1 = ActiveSheet.OLEObjects(1).Object ---> this works on sheet but not works on form
rng.AutoFilter field:=13, Criteria1:=y
rng.AutoFilter field:=12, Criteria1:=x
Worksheets.Add
rng.SpecialCells(xlCellTypeVisible).Copy Range("a1")
vArr = ActiveSheet.UsedRange
With ListBox1
.List = (vArr)
End With
ActiveSheet.Delete
Worksheets("TRAINING").AutoFilterMode = False
'rng.AutoFilter.Clear
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True
End Sub
我發現這個代碼,但這個創造了新的列表框,但不填充列表框與數據,只有標題,沒有找到什麼是不正確的,與此代碼我怎麼能彌補現有列表框?
Sub MyListBox()
Dim rng As Range
Dim vArr As Variant
Dim ListBox1 As MSForms.Control
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Set rng = Range("TestMaterial")
Set ListBox1 = frmplan.Controls.Add("Forms.ListBox.1") ---> adds new Listbox to form even I have some one with name "Listbox1"
rng.AutoFilter field:=13, Criteria1:=txtsdept.Value
rng.AutoFilter field:=12, Criteria1:=txtsgrade
Worksheets.Add
rng.SpecialCells(xlCellTypeVisible).Copy Range("a1")
vArr = ActiveSheet.UsedRange
With ListBox1
.List = (vArr)
End With
ActiveSheet.Delete
Worksheets("TRAINING").AutoFilterMode = False
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True
End Sub
如果代碼在用戶表單中,則不需要變量 - 只需按名稱引用列表框:'ListBox1.List = vArr' – Rory
上面的代碼是正確的,它將正常工作。請檢查所選範圍是否包含數據,因爲UserRange數據已添加到ListBox中。另外我相信TestMaterial是一個有效的範圍(例如,「A1:A5」) –
第二個代碼是否可以填充現有的Listbox而不創建新的?在第一個代碼中,我可以創建一個Listbox並填充它,但是在第二個代碼中,即使我有一個Listbox代碼也會創建一個新代碼。 –