如何根据 table 值填充单元格内下拉列表?

How can I populate an in-cell dropdown list based on table values?

我正在尝试使用 VBA 创建动态单元格内下拉列表。目前,我根据输入的值填充了下拉列表。然而,正如我预见到这个程序的使用越来越多,我想使下拉列表动态化。有没有办法让 VBA 循环通过 table 并根据第 1 列中的值填充下拉列表(例如)?

下面是我目前的代码;如您所见,公式值是静态的,基于我硬编码的值:

Sub Dropdown_Setup()
'Setup appropriate template dropdowns on 'template' sheet

    Set wB = ThisWorkbook
    Set tempSht = ThisWorkbook.Sheets("Template")

'Populate 'machine' dropdown
    With tempSht.Range("$B").Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
            Formula1:="H1 - EOS M280, H2 - SLM, H4 - CL M2, H5 - EOS M400, H6 - SLM 2.0"
        .IgnoreBlank = True
        .InCellDropdown = True
    End With

End Sub

如有任何帮助,我们将不胜感激。

您可以遍历列表对象第一列中的每个单元格,并构建一个可以分配给 Formula1 进行验证的逗号分隔字符串。

我假定 Sheet2 包含您的列表对象,并且该列表对象名为 Table1。相应地更改这些名称。

此外,您已经定义了 wB,但是您没有在代码中使用它。由于不是很需要,所以我删除了它。

Sub Dropdown_Setup()
'Setup appropriate template dropdowns on 'template' sheet

'Set the source table
    Dim sourceTable As ListObject
    Set sourceTable = ThisWorkbook.Sheets("Sheet2").ListObjects("Table1")

'Get the items from the first column of the source table
    Dim itemsList As String
    Dim currentCell As Range
    itemsList = ""
    For Each currentCell In sourceTable.ListColumns(1).DataBodyRange
        If Len(currentCell.Value) > 0 Then
            itemsList = itemsList & "," & currentCell.Value
        End If
    Next currentCell
    itemsList = Mid(itemsList, 2)

'Set the template sheet
    Dim tempSht As Worksheet
    Set tempSht = ThisWorkbook.Sheets("Template")

'Populate 'machine' dropdown
    With tempSht.Range("$B").Validation
        .Delete
        .Add _
            Type:=xlValidateList, _
            AlertStyle:=xlValidAlertStop, _
            Formula1:=itemsList
        .IgnoreBlank = True
        .InCellDropdown = True
    End With

End Sub