简体   繁体   English

我将如何遍历表头以填充 ComboBox 下拉列表?

[英]How would I loop through table headers to populate a ComboBox drop-down list?

I'm trying to loop through a table's header row to populate a UserForm's ComboBox drop-down list.我正在尝试遍历表的标题行以填充用户窗体的 ComboBox 下拉列表。

The header row of my table is the second row of my worksheet.我的表格的标题行是我的工作表的第二行。

My thought was to use the intersect() function to check whether my loop is still inside my header range and if not then exit the loop.我的想法是使用 intersect() 函数来检查我的循环是否仍在我的标题范围内,如果不是,则退出循环。
If the intersect is true, then add the current cell.value to the ComboBox list.如果 intersect 为真,则将当前cell.value添加到 ComboBox 列表中。

I am also trying to store the header row into an array, but I haven't been able to start my loop to see if my code sets the header row values to an array.我也试图将标题行存储到一个数组中,但我无法启动我的循环来查看我的代码是否将标题行值设置为一个数组。
The error that I am getting is我得到的错误是

'Object variable or with block variable not set' '对象变量或块变量未设置'

Option Explicit

Dim ws As Worksheet

Public Tbl1 As ListObject


Private Sub ComboBox_DropButtonClick()

Set ws = ActiveSheet
Set Tbl1 = ws.ListObject("Table1")

Dim i As Integer
Dim Tbl1HeaderArray() As Variant

i = 1
ComboBox.RowSource = ""

Do Until i = -1

    If Intersect(Tbl1.HeaderRowRange(), ws.Cells(2, i)) Is Nothing Then
        i = -1
    Else
        ComboBox.AddItem (ws.Cells(2, i).Value)
        Tbl1HeaderArray(i - 1) = ws.Cells(2, i).Value
        i = i + 1
    End If

Loop

End Sub

I've tried a couple different approaches, but this is the most promising.我尝试了几种不同的方法,但这是最有希望的。 I'm open to different routes of accomplishing my task.我对完成任务的不同途径持开放态度。

Fill Combo Box With Table Headers用表格标题填充组合框

The Code编码

Option Explicit

Private Sub ComboBox1_DropButtonClick()
    
    Dim ws As Worksheet
    Set ws = ActiveSheet
    
    Dim tbl As ListObject
    Set tbl = ws.ListObjects("Table1")
    
    With ComboBox1
        '.Clear
        .Column = tbl.HeaderRowRange.Value
    End With
    
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM