Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 如何基于表格值填充单元格内下拉列表?_Excel_Vba_Listobject - Fatal编程技术网

Excel 如何基于表格值填充单元格内下拉列表?

Excel 如何基于表格值填充单元格内下拉列表?,excel,vba,listobject,Excel,Vba,Listobject,我正在尝试使用VBA创建一个动态的单元格内下拉列表。目前,我已经根据输入的值填充了下拉列表。然而,由于我预见到这个程序的使用会越来越多,我想让下拉列表变得动态。是否有方法让VBA循环表并根据第1列中的值填充下拉列表(例如) 下面是我目前拥有的代码;如您所见,公式值基于我硬编码的值是静态的: Sub Dropdown_Setup() 'Setup appropriate template dropdowns on 'template' sheet Set wB = ThisWorkboo

我正在尝试使用VBA创建一个动态的单元格内下拉列表。目前,我已经根据输入的值填充了下拉列表。然而,由于我预见到这个程序的使用会越来越多,我想让下拉列表变得动态。是否有方法让VBA循环表并根据第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$15").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

非常感谢您的帮助。

您可以循环查看listobject第一列中的每个单元格,并构建一个逗号分隔的字符串,该字符串可以分配给
公式1
,以进行验证

我假设Sheet2包含listobject,listobject的名称为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$15").Validation
        .Delete
        .Add _
            Type:=xlValidateList, _
            AlertStyle:=xlValidAlertStop, _
            Formula1:=itemsList
        .IgnoreBlank = True
        .InCellDropdown = True
    End With

End Sub