Avatar of nainil
nainil
Flag for United States of America asked on

Generate Comma Separated string from columns based on condition in Excel using VBA

I have three columns in Excel:

 
Sheet		Errors			Status
Codes		15 Errors found		Yes
Names		250 Errors found	No
Details		No Error		Yes
Sheet4		No			No

Open in new window


I want to generate a comma separated string from the first column where status='Yes'.

For eg, 'Codes, Details' should be generated
Microsoft ExcelVB ScriptProgramming

Avatar of undefined
Last Comment
nainil

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
rspahitz

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Patrick Matthews

This seems to be working for me.  It relies on the AUtoFilter to do its voodoo:

Sub MakeTheString()
    
    Dim LastR As Long
    Dim LastC As Long
    Dim Result As String
    
    Result = "<No data found!>"
    
    With ActiveSheet
        LastR = .Cells(.Rows.Count, 1).End(xlUp).Row
        LastC = .Cells(1, .Columns.Count).End(xlToLeft).Column
        .Cells(1, LastC + 1) = "Original"
        With .Range(.Cells(2, LastC + 1), .Cells(LastR, LastC + 1))
            .Formula = "=ROW(A1)"
            .Value = .Value
        End With
        .[a1].Sort Key1:=.[c1], Key2:=.Cells(1, LastC + 1), Order1:=xlAscending, Order2:=xlAscending, _
            Header:=xlYes
        .[a1].AutoFilter
        .[a1].AutoFilter 3, "Yes", xlAnd
        On Error Resume Next
        Result = Join(Application.Transpose(.Range(.Cells(2, 1), .Cells(LastR, 1)).SpecialCells(xlCellTypeVisible)), ", ")
        On Error GoTo 0
        .[a1].AutoFilter
        .[a1].Sort Key1:=.Cells(1, LastC + 1), Order1:=xlAscending, Header:=xlYes
        .Cells(1, LastC + 1).EntireColumn.Delete
    End With
    
    MsgBox Result
    
End Sub

Open in new window

nainil

ASKER
Works as expected.
Thank you for your help!
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes