【发布时间】:2015-08-07 22:34:16
【问题描述】:
我在 Excel 中的用户表单上有两个组合框。当我选择第一个组合框时,它会过滤当前工作表上的行并在组合框2 中显示值。
我希望combobox2 成为一个多列组合框,这样我就可以将多个值从一个工作表复制并粘贴到另一个工作表,但我无法将多个值放入combobox2。这是我一起破解的代码。当我更改组合框 1 中的值但组合框 2 显示单个值时,我能够过滤结果:
Private Sub ComboBox1_Change()
Me.ComboBox2.Clear
'filter the results in combo box 2 when the user selects the different options in combo box 1
Dim wb As Workbook
Dim ws As Worksheet
Dim copyFrom As Range, aCell As Range
Dim lRow As Long
Dim strSearch As String
Set wb = ThisWorkbook
'~~> Set this to the worksheet where the autofilter is applied
Set ws = wb.Worksheets("RegEvents")
'~~> Filter Column on text in Combo box 1
strSearch = ComboBox1.Value
With ws
'~~> Remove any filters
.AutoFilterMode = False
With .Range("RegEvents_WorksheetData")
.AutoFilter Field:=Range("RegEvents_Action").Column, Criteria1:="=" & strSearch
'~~> Identify the filtered range
Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible)
'~~> Add values from filtered search to Combobox2
For Each aCell In copyFrom
If aCell.Value <> "" And aCell.Column = Range("RegEvents_EventID").Column Then
ComboBox2.AddItem (aCell.Value)
End If
If aCell.Value <> "" And aCell.Column = Range("RegEvents_Event").Column Then
ComboBox2.AddItem (aCell.Value)
End If
Next
End With
'~~> Remove any filters
.AutoFilterMode = False
End With
End Sub
Private Sub UserForm_Initialize()
'Used to create an array
Dim listItems As Variant
Me.ComboBox1.ListIndex = -1 ' -1 = no items selected
Label1.Caption = "Action"
Label2.Caption = "Event"
listItems = Range("CatogriesAction")
With ComboBox1
'Loops through the array and only adds non blank values to the combo box
For i = 1 To UBound(listItems, 1)
If Len(Trim(listItems(i, 1))) > 0 Then
.AddItem listItems(i, 1) ' populate the listbox
End If
Next i
.ListIndex = 0 ' -1 = no items selected, set to 0 to select the first item
End With
'Set number of columns for combobox 2
With Me.ComboBox2
.ColumnCount = 2
.BoundColumn = 2
.ColumnWidths = ".5 in; .5 in"
End With
End Sub
【问题讨论】:
-
据我所知,组合框在打开时可以显示多列,但在组合框处于非活动状态(折叠)时只能显示一列。这一列是可以在属性中定义的“绑定”列。也许列表框会更适合?像这样你可以显示更多的列。