Last active
August 22, 2023 15:46
-
-
Save maximpertsov/39682cf7a2b799e4fa27 to your computer and use it in GitHub Desktop.
Join VBA collection items into a string
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 CollectionToString(C As Collection, Optional Delimiter As String, Optional TrailingDelimiter As Boolean) As String | |
' Join a collection into a single string | |
' OPTIONAL: choose delimiter and specify whether to include a trailing delimiter (e.g. "a;b;c" vs "a;b;c;", where ";" is the delimiter) | |
' Transfer collection to array | |
CollectionToString = Join(CollectionToArray(C, 0, C.Count + IIf(TrailingDelimiter, 1, 0)), Delimiter) ' See Referenced Gists below | |
End Function | |
Function CollectionToArray(C As Collection, Optional StartIdx As Long, Optional Size As Long) As Variant | |
' Convert a collection into an array | |
Dim A() As Variant | |
Dim Ci As Variant ' Collection element | |
Dim i As Long | |
' Make sure Size is not less than collection size | |
If Size < C.Count Then Size = C.Count | |
' Transfer collection to array | |
ReDim A(StartIdx To StartIdx + Size - 1) | |
For Each Ci In C | |
A(i) = Ci | |
i = i + 1 | |
Next | |
CollectionToArray = A | |
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
Sub CollectionToStringTest() | |
Dim C As Collection: Set C = New Collection | |
C.Add "a" | |
C.Add "b" | |
C.Add "c" | |
Debug.Print "No delimiter: " & CollectionToString(C) ' No delimiter: abc | |
Debug.Print "No trailing delimiter: " & CollectionToString(C, ",") ' No trailing delimiter: a,b,c | |
Debug.Print "Trailing delimiter: " & CollectionToString(C, ",", True) ' Trailing delimiter: a,b,c, | |
End Sub |
Great catch! Feel free to edit this gist with your fix if you like.
Glad this has been helpful for you otherwise.
Thank you for the very helpful functionality
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey There, I used this for an automation, and it worked great! Thanks for making this available. I did notice that when if I ran the macro more than once the contents of A() were preserved, so the list grew and grew with each run. I was able to prevent this by adding Erase A() after the variable declarations in CollectionToArray. I wanted to note this incase anyone else needed the same behavior. Thanks again!