Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

excel - Concatenate top row cells if column below has 1

I'm looking at a large database of 1s and 0s with named columns, like this:

red    blue   green  orange purple
────── ────── ────── ────── ──────
0      0      1      0      1 
0      1      0      0      0 

I want to concatenate all the headings (by row) where the row has a "1" below that heading. So ideally the first one would equal "green, purple" and the second would just read "blue". I have a large amount of data so anything with nesting of a hundred "IF" functions doesn't make sense.

I've tried

=IF(B1:B5=1, CONCATENATE(A1:A5), "")

and a couple things close to that, but I'm not finding an obvious way to get it. I also don't really have time or enough knowledge to deal with VBA. I appreciate all help, thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

String concatenation over more than a few cells is best left to a VBA User Defined Function (aka UDF) even without setting criteria. Your situation of "nesting of a hundred "IF" functions" would certainly put it in this category.

Tap Alt+F11 and when the VBE opens, immedaitely use the pull-down menus to Insert ? Module (Alt+I,M). Paste the following into the new pane titled something like Book1 - Module1 (Code).

Public Function conditional_concat(rSTRs As Range, rCRITs As Range, Optional sDELIM As String = ", ")
    Dim c As Long, sTMP As String
    For c = 1 To Application.Min(rSTRs.Cells.Count, rCRITs.Cells.Count)
        If CBool(rCRITs(c).Value2) Then _
            sTMP = sTMP & rSTRs(c).Value & sDELIM
    Next c
    conditional_concat = Left(sTMP, Application.Max(Len(sTMP) - Len(sDELIM), 0))
End Function

Tap Alt+Q to return to your worksheet. Use this UDF like any native Excel worksheet function. The syntax is,

conditional_concat(<range of strings>, <range of conditions>, [optional] <delimiter as string>)

??????Conditional String Concatenation

The formula in G2 is,

=conditional_concat(A$1:E$1, A2:E2)

Fill down as necessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...