Last active
January 23, 2016 18:21
-
-
Save maximpertsov/d132d9c2525ef07b061d to your computer and use it in GitHub Desktop.
Concatenate a range of Excel cells into a single string specified by a given criteria or condition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function ConcatRangeIf(Rc As Range, Criterion As String, Rv As Range, Optional Delimiter As String) | |
' Concatenate cells into a single string specified by a given criteria or condition | |
Dim C As Collection: Set C = New Collection ' Collection of values to be included in final string | |
Dim Ac() As Variant: Ac = Rc ' Criterias | |
Dim Av() As Variant: Av = Rv ' Values | |
Dim i As Long | |
Dim j As Long | |
For i = LBound(Ac, 1) To UBound(Ac, 1) | |
For j = LBound(Ac, 2) To UBound(Ac, 2) | |
' Bypass criteria of empty cells if specified | |
If Len(Ac(i, j)) > 0 Then | |
' Evaluate criteria | |
Select Case Left(Criterion, 1) | |
Case ">", "<", "=": | |
If Application.Evaluate(Rc(i, j) & Criterion) Then C.Add Av(i, j) | |
Case Else: | |
If Criterion = Rc(i, j) Then C.Add Av(i, j) | |
End Select | |
End If | |
Next j | |
Next i | |
ConcatRangeIf = Join(CollectionToArray(C), Delimiter) | |
End Function |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Private Function FilterCollection(C As Collection, Criterion As String) As Collection | |
' Filter collection C based on a criterion | |
Dim NewC As Collection ' Filtered collection | |
Dim Ci As Variant ' Collection element | |
For Each Ci In C | |
' Evaluate criteria | |
Select Case Left(Criterion, 1) | |
Case ">", "<", "=": | |
If Application.Evaluate(Ci & Criterion) Then NewC.Add Ci | |
Case Else: | |
If Criterion = Ci Then C.NewC Ci | |
End Select | |
Next Ci | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment