Concatenating a variable range in VBA

Woffy

New Member
Joined
Oct 21, 2011
Messages
9
I have a macro which will return a list of text values in a column. The length of the list can vary according to the data to which the macro is applied. I want to concatenate the values, split by ", " (as the next step in the macro, rather than by hand).

I understand how to do this if I know the length of the list (similarly to this thread: http://www.mrexcel.com/forum/showthread.php?t=479) but I want to know if there is a way to concatenate all the cells in a range using a single command, rather than by refering to each cell separately (as I don't know how many cells there will be).

Thanks
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
In vba you can have Myrange.rows.count - which will count the number of rows in a range.

Hence broadly speaking you have:-

Code:
dim my_range as range
dim no_of_rows as long
dim overall_string as string
dim i as long

set my_range = Sheets("Sheet1").range("A1:2000")
no_of_rows = my_range.rows.count

for i = 1 to no_of_rows
overall_string = overall_string & my_range(i,1)
next i
Note that this is for guidance only - you'll need to modify for your situation. Thanks

Regards

Kaps
 
Upvote 0
Great, I'll try that. Many thanks for your help.

EDIT: Works brilliantly, thank you. I have used

Code:
overall_string=overall_string & my_range(i,1) & ", "

for all but the last i in order to incorporate the comma.
 
Last edited:
Upvote 0

Forum statistics

Threads
1,216,089
Messages
6,128,760
Members
449,466
Latest member
Peter Juhnke

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top