将第二列添加到 Excel 用户窗体中的动态行源

Adding second column to a dynamic rowsource in Excel Userform

我正在尝试用第二列填充用户表单以使其更加用户友好。目前它显示的是身份证号码,但我还希望它显示姓名。

我在这个帖子 () 中找到了一个答案,它似乎可以满足我的要求,但我不能完全让代码与我的匹配,因为我使用的是动态引用填充组合框,而不是静态引用。

这是我对初始化宏的尝试:

Dim C As Range
Sheets("Consent_Outcome").Activate
Range("A2", Range("A" & Rows.Count).End(xlUp)).Name = "Dynamic"
Range("L2", Range("L" & Rows.Count).End(xlUp)).Name = "Dynamic2"
Me.cboURN.RowSource = "Dynamic"

For Each C In cboURN
Me.cboURN.Offset(1, 0) = "Dynamic2"

我希望它用 L 列的值填充组合框中的第二列,显然我应该通过将第二列的值设置为 ComboBox1.Column(1,{rowIndex}) = 'the value'`,但我无法让它与动态参考一起使用。谁能建议如何做到这一点?

由于您将 hard-coded "A2" 作为范围的顶部,我了解到您假设数据将始终从第二行开始。如果将范围 L2 分配给范围变量,则可以使用递增循环将范围变量的值分配给适当的列表值,然后 .Offset(1,0) 并重新分配范围变量以向下递增列。

注意:我的代码应该与 excel 组合框一起使用;我不知道它是否适用于 Access 组合框。

假设 cboURN 是您的组合框:

Dim C As Range
Dim index as Integer

Sheets("Consent_Outcome").Activate
Range("A2", Range("A" & Rows.Count).End(xlUp)).Name = "Dynamic"
' Unnecessary: Range("L2", Range("L" & Rows.Count).End(xlUp)).Name = "Dynamic2"
Me.cboURN.RowSource = "Dynamic"

Set C = Range("L2")

With cboURN 'Or Me.cboURN; you can reference named controls without the preceding "Me."
    For index = 0 to .ListCount - 1
        .List(index, 1) = C 'Or C.Value2
        Set C = C.Offset(1,0)
    Next index
End With

或者,您也应该能够使用此代码来填充组合框(尽管如果您需要按特定顺序添加项目,此选项可能不是最佳选择):

Dim C As Range
Dim cell As Range
Dim index as Integer

Sheets("Consent_Outcome").Activate
Set C = Range("A2", Range("A" & Rows.Count).End(xlUp))

With cboURN 'Or Me.cboURN; you can reference named controls without the preceding "Me."
    For each cell in C 
        .AddItem cell
        .List(.ListCount - 1, 1) = cell.Offset(0, 11) 'Offset 11 columns to column L
    Next cell
End With