我有下拉要求从lookupDept工作簿上的两列中提取信息并合并。比如我有:
deptCode deptName
BS Business School
CD Design and Technology
CG Chemical Engineering
CM Chemistry
CO Computer Science
我已经设法解决了有关从组合框中使用的两个spead-sheet列中提取的信息的问题。但不幸的是,组合框列表现在看起来像这样:
BS
CD
CG
CM
Business School
Design and Technology
Chemical Engineering
Chemistry
当我希望它看起来像这样:
BS Business School
CD Design and Technology
CG Chemical Engineering
CM Chemistry
这需要合并两列信息(列已命名为 deptCode 和 deptName ),但我不太清楚如何完成它。这是我到目前为止所尝试的,代码列出了两列的信息而不是合并它们:
Private Sub UserForm_Initialize()
Dim c_deptCode As Range
Dim c_deptName As Range
Dim ws_dept As Worksheet
Set ws_dept = Worksheets("lookupDept")
For Each c_deptCode In ws_dept.Range("deptCode")
With Me.cbo_deptCode
.AddItem c_deptCode.Value
.List(.ListCount - 1, 1) = c_deptCode.Offset(0, 1).Value
End With
Next c_deptCode
For Each c_deptName In ws_dept.Range("deptName")
With Me.cbo_deptCode
.AddItem c_deptName.Value
End With
Next c_deptName
End Sub
答案 0 :(得分:1)
看起来主要的问题是你要将第二个范围与第一个范围完全分开(我知道这是你的问题,所以我会道歉指出明显的:))。在任何情况下,您可以执行的操作类似于以下内容 - 基本上组合两个范围中的值,然后将该单个值添加到下拉列表中。主要的变化是添加两个新变量(表示包含命名范围值的数组)并将For
循环压缩为一个。
Private Sub UserForm_Initialize()
Dim c_deptCode As Range
Dim c_deptName As Range
Dim deptCodes As Variant
Dim deptNames As Variant
Dim ws_dept As Worksheet
Set ws_dept = Worksheets("lookupDept")
' Assign each range to an array containing the values
deptCodes = Choose(1, ws_dept.Range("deptCode"))
deptNames = Choose(1, ws_dept.Range("deptName"))
' Note that this blindly uses deptCode as a sort of control.
' This could be handled a bit better, but should work for this case
For i = 1 To ws_dept.Range("deptCode").Rows.Count
' Create the combined name (code + space + name)
CombinedName = deptCodes(i, 1) & " " & deptNames(i, 1)
cbo_deptCode.AddItem CombinedName
Next i
End Sub
答案 1 :(得分:1)
将组合框的ColumnCount
属性设置为2
,并将数据作为二维数组加载到List
属性中
您还可以使用ColumnWidths
Private Sub UserForm_Initialize()
Dim c_deptCode As Range
Dim c_deptName As Range
Dim ws_dept As Worksheet
Dim aDat() As Variant
Dim i As Long
Set ws_dept = Worksheets("lookupDept")
Set c_deptCode = ws_dept.Range("deptCode")
Set c_deptName = ws_dept.Range("deptName")
aDat = c_deptCode
ReDim Preserve aDat(1 To UBound(aDat, 1), 1 To 2)
For i = 1 To UBound(aDat, 1)
aDat(i, 2) = c_deptName.Cells(i, 1)
Next
With cbo_deptCode
.ColumnCount = 2
.ColumnWidths = "20;50"
.List = aDat
End With
End Sub