Excel:宏以在单元格中有条件地列出列表中的所有值

时间:2016-03-28 03:30:27

标签: excel macros

我正在尝试编写一个宏,我需要列出属于特定项目的所有资源及其角色。 例如:

Resource    Project 1   Project 2   Project 3
X1          Manager     Team Lead   
X2          Analyst                 Team Lead
X3                      Consultant  
X4          BA                      Consultant

然后结果应该是:

            List
Project 1   X1, X2 and X4
Project 2   X1 and X3
Project 3   X2 and X4

请建议我应该如何实现这一目标。感谢。

1 个答案:

答案 0 :(得分:1)

试试这个UDF。

<强> Module1 (Code)

Option Explicit

Function listProjectResources(rng As Range, rsc As Range)
    Dim tmp As String, r As Long, c As Long, n As Long
    Set rsc = rsc.Resize(rng.Rows.Count, rng.Columns.Count)
    For r = 1 To rng.Rows.Count
        For c = 1 To rng.Columns.Count
            If Not IsEmpty(rng.Cells(r, c)) Then
                tmp = tmp & _
                      IIf(CBool(Len(tmp)), " and ", vbNullString) & _
                      rsc.Cells(r, c).Value2
                n = n + 1
            End If
        Next c
    Next r

    If n > 2 Then _
        tmp = Replace(tmp, " and ", Chr(44) & Chr(32), 1, n - 2)

    listProjectResources = tmp
End Function

在G4中使用,

=listProjectResources(INDEX($B$2:$D$5, 0, MATCH(F4, B$1:D$1, 0)), A$2:A$5)

Concat_Project_Resources