Convert range to comma delimited string

五迷三道 提交于 2020-04-10 07:26:07

问题


If I had a column like this:

Col1
abc
def
ghi
jkl

How can I convert it to a string like this?:

"abc,def,ghi,jkl"

回答1:


You can use the Join() function to join all the elements of a 1 dimensional array with a delimiter.

The Transpose() function is used below to form the dimensional array (this approach works on a single column or row).

Sub Main()
    Dim arr
    arr = Join(Application.Transpose(Range("A2:A5").Value), ",")
    MsgBox arr
End Sub

or as an UDF

Public Function Merge(r As Range) As String
    Merge = Join(Application.Transpose(r.Value), ",")
End Function



回答2:


Just in case you need heavier machinery use one of the solutions provided in the answer below. I had similar challenge for ranges containing milion of cells. In such cases JOIN will lead to crash.

Check the question here: Turn Excel range into VBA string

I have tested all the approaches provided in the above link. Solutions based on function JOIN have slow performance, or even lead to crash.

Ordinary loop through all the cells is way faster than JOIN function. The sting builder in accepted answer is even faster. With string builder, the strings consisting of millions of cells are build in seconds. This is the solution I have end up with.




回答3:


Double-transpose works for doing string join on single-row values. Thanks @user2140173 and @brettdj!

debug.print join(Application.Transpose(Application.Transpose(Range("A1:G1").Value)),",")



来源:https://stackoverflow.com/questions/22349945/convert-range-to-comma-delimited-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!