如何在Excel 2016中使用VBA创建复杂的依赖下拉列表?

时间:2017-02-28 13:39:41

标签: excel vba excel-vba dropdown

我在名为Parts的工作表中有以下数据。

Parts Worksheet

在名为Planning的不同工作表中,我有以下数据:

Planning Worksheet

在上面的规划工作表中,单元格D3是一个允许选择显示语言的下拉列表。目前的选择是"英语"和"日语"。 A列的单元格也是下拉列表,允许选择维度。

我想要做的是创建一个下拉列表:

  1. 取决于A列中的单元格。下拉列表应根据相应A单元格的值从“零件工作表”中过滤数据。
  2. 也依赖于D3 Cell。下拉列表应显示"英文说明"如果D3是"英语"或"日语描述"如果D3是"日语"
  3. 选择后,下拉列表中的数据应为部分而不是说明。换句话说,它应该像HTML中的选择标记一样。
  4. 我是VBA的新手,经过大量的搜索,我无法弄清楚如何做到这一点。我真的很感激一个详细的答案。提前谢谢!

    编辑:

    最终的零件工作表将至少10,000行。用户无法手动创建命名列表。出于这个原因,我想我应该使用VBA。

1 个答案:

答案 0 :(得分:0)

我不确定你是否尝试了这个,因为我从昨天开始将你的问题作为答案发布。

当您在列B上选择单元格时,代码会根据A列中的值动态创建验证下拉列表,从而完成所需的一切。下拉列表根据语言显示产品代码和说明。选择产品代码并从单元格中删除验证后,将删除说明。

虽然代码确实做了你需要的所有东西,但它并不完美,但是它给你一个很大的开端,它应该与你的工作表名称等一起使用,如果你复制并粘贴它并尝试一下。

Dim CHANGING_VAL As Boolean 'Global Variable that can be set to prevent the onchange being fired when the Macro is removing the description from the dropdown.

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)


    If Target.Column = 2 And CHANGING_VAL = False Then
        CHANGING_VAL = True
        If InStr(1, Target.Value, "~") > 2 Then
            Target.Value = Left(Target.Value, InStr(1, Target.Value, "~") - 2)
        End If
        Target.Validation.Delete
        Target.Font.Color = RGB(0, 0, 255)
        CHANGING_VAL = False
    End If

End Sub

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    If Target.Column = 2 Then
        If Target.Offset(0, -1) <> "" Then
            strValidList = ""
            For intRow = 1 To 10000
                If Sheets("Parts").Cells(intRow, 1) = Target.Offset(0, -1) Then
                    If Sheets(Target.Parent.Name).Cells(3, 4) = "English" Then
                        strValidList = strValidList & Sheets("Parts").Cells(intRow, 2) & " ~ " & Sheets("Parts").Cells(intRow, 3) & ", "
                    Else
                        strValidList = strValidList & Sheets("Parts").Cells(intRow, 2) & " ~ " & Sheets("Parts").Cells(intRow, 4) & ", "
                    End If
                End If
            Next

            If strValidList <> "" Then
                strValidList = Left(strValidList, Len(strValidList) - 2)

                Target.Select

                With Selection.Validation
                    .Delete
                    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=strValidList
                    .IgnoreBlank = True
                    .InCellDropdown = True
                    .InputTitle = ""
                    .ErrorTitle = ""
                    .InputMessage = ""
                    .ErrorMessage = ""
                    .ShowInput = True
                    .ShowError = True
                End With
            End If
        End If
    Else
        Sheets(Target.Parent.Name).Range("B:B").Validation.Delete
    End If

End Sub