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

时间:2017-02-27 14:01:32

标签: excel vba excel-vba nested dropdown

我想在以下工作表的B列中创建一个下拉列表(规划):

Planning Worksheet

D3 Cell包含要显示的语言。当在A列中输入维度时,我想要一个由输入的维度过滤的部分下拉列表。

数据包含在以下工作表(数据)中:

Data Worksheet

为了使事情复杂化,我希望下拉列表根据规划中选择的语言显示数据工作表中的内容。$ D3(如果选择英语显示绿色文本,如果选择日语,则显示红色文本)。只有具有Dimension和Label ==“index”的行应出现在下拉列表中(2,8,15,...)。选择后,下拉列表应显示零件数据(蓝色)。

如何在VBA中构建这样的下拉列表?

1 个答案:

答案 0 :(得分:1)

这是一个有趣的问题,当在A列中输入维度代码时,我使用在B列中的单元格上设置验证的方法来使用下面的代码。

选择一个选项后,B列中文本的颜色会变为蓝色,但是您想要的绿色和红色文字实际上是不可能的,因为在单元格下拉列表中始终显示黑色,而不管单元格是什么&#39 ; s字体颜色。

代码并不完美,但更多只是概念验证,可以为您提供一个良好的开端。

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 300
                If Sheets("Data").Cells(intRow, 1) = Target.Offset(0, -1) Then
                    If Sheets(Target.Parent.Name).Cells(3, 4) = "English" Then
                        strValidList = strValidList & Sheets("Data").Cells(intRow, 2) & " ~ " & Sheets("Data").Cells(intRow, 3) & ", "
                    Else
                        strValidList = strValidList & Sheets("Data").Cells(intRow, 2) & " ~ " & Sheets("Data").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