Excel填充信息取决于两个动态下拉菜单

时间:2018-07-13 11:15:38

标签: excel vba dynamic dropdown

我正在寻找以下问题的解决方案:
我有一个documentation,其中包含有关多个客户的信息,每个客户都有多个项目。客户+项目名称的组合是唯一的。

sheet上,我希望能够:

  1. 从动态下拉列表中选择没有重复的客户(我已经做到了)
  2. 然后显示第二个下拉列表,仅显示所选客户的那些项目
  3. 在单元格(C5:C7)中自动填充信息

由于数据表的内容是动态的,将包含大量数据,因此命名表是不可选择的。

如果有人对如何解决这个问题有了个主意,我将不胜感激!

1 个答案:

答案 0 :(得分:0)

可以通过VBA实现。我已经编写了以下代码并为我工作。

输入表:

enter image description here

尝试以下代码。

Sub CustomerAndProject()

Dim Customer As String, Project As String, Info1 As String, Info2 As String, Info3 As String

Dim TotalCustomers As Integer, m As Integer

m = 1

'Get Total customers

TotalCustomers = Worksheets("Sheet1").Range("A1").End(xlDown).Row

'First loop to pick customers

For i = 2 To TotalCustomers

Customer = Worksheets("Sheet1").Range("A" & i).Value

'Second loop to pick the projects related to customer

For k = 2 To TotalCustomers

Project = Worksheets("Sheet1").Range("B" & k).Value

'Function r=to validate the duplicate customers and projects

If CustomerValidationForDuplication(Project, Customer, TotalCustomers) = False Then

'Third loop to pick and paste info data related to customer and project

For j = 2 To TotalCustomers

If Worksheets("Sheet1").Range("A" & j).Value = Customer And Worksheets("Sheet1").Range("B" & j).Value = Project Then

Worksheets("Sheet2").Cells(1, m).Value = Customer

Worksheets("Sheet2").Cells(2, m).Value = Project

        If IsEmpty(Worksheets("Sheet1").Range("C" & j).Value) Then

            Else: Info1 = Worksheets("Sheet1").Range("C" & j).Value

                Worksheets("Sheet2").Cells(3, m).Value = Info1

               End If

                If IsEmpty(Worksheets("Sheet1").Range("D" & j).Value) Then

                    Else: Info2 = Worksheets("Sheet1").Range("D" & j).Value

                    Worksheets("Sheet2").Cells(4, m).Value = Info2

                      End If

                        If IsEmpty(Worksheets("Sheet1").Range("E" & j).Value) Then

                            Else: Info3 = Worksheets("Sheet1").Range("E" & j).Value

                            Worksheets("Sheet2").Cells(5, m).Value = Info3

                             End If

                     End If

                 Next

             m = m + 1

        End If

    Next

Next


End Sub


Function CustomerValidationForDuplication(ProjectToBeVerified As String, CustomerToBeVerified As String, TotalCustomers As Integer) As Boolean

For l = 1 To TotalCustomers

If ProjectToBeVerified = Worksheets("Sheet2").Cells(2, l) Then

For m = 1 To TotalCustomers

If CustomerToBeVerified = Worksheets("Sheet2").Cells(1, m) Then

CustomerValidationForDuplication = True

Exit For


Else

CustomerValidationForDuplication = False

End If

Next

Else

CustomerValidationForDuplication = False

End If

If CustomerValidationForDuplication = True Then Exit For

Next


End Function

输出表:

enter image description here

让我知道它是否对您有用。

注意:我是VBA的新手,所以我的代码不会友好。欢迎进行编辑。