0

我有下拉需要从 lookupDept 工作簿上的两列中提取信息并合并。例如我有:

deptCode deptName
BS       Business School
CD       Design and Technology
CG       Chemical Engineering
CM       Chemistry
CO       Computer Science

我已经设法解决了关于从两个电子表格列中提取信息以在组合框中使用的问题。但不幸的是,组合框列表现在看起来像这样:

BS
CD
CG
CM
Business School
Design and Technology
Chemical Engineering
Chemistry

当我希望它看起来像这样时:

BS Business School
CD Design and Technology
CG Chemical Engineering
CM Chemistry

这需要合并两列信息(列已命名为deptCodedeptName),但我不太确定如何完成它。这是我迄今为止尝试过的,来自两列的代码列表信息,而不是合并它们:

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
4

2 回答 2

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
于 2012-10-07T08:57:09.213 回答
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
于 2012-10-07T09:02:49.920 回答