7

first of all, new to VBA.

I am implementing this solution how-to-merge-all-column-into-one-cell-in-excel[stackoverflow], but have a follow-on.

A1:I
A2:am
A3:a
A4:boy

my output is: Iamaboy but I would like in one cell:

I
am
a
boy

Functions do not seem to return strings with vbNewLine, chr(10) or chr(13)...

Community
  • 1
  • 1
posop
  • 511
  • 2
  • 7
  • 17

7 Answers7

3

One line of code:

Range("B1").Formula = join(application.transpose(Range("A1:A4")),vblf)
Dan Donoghue
  • 6,056
  • 2
  • 18
  • 36
2

The answer is, as tlewin said

=ConcatenateRange(A1:A4,CHAR(10))

Or alternatively, using [alt-enter] you could write it like this

=ConcatenateRange(A1:A4,"
")

"But wait," you say, "I tried that and it does not work!"
Well, you see, when you manually enter something like I[alt-enter]am[alt-enter]a[alt-enter]boy in Excel, or even execute a statement such as [A1] = "I" & vbNewLine & "am" Excel automatically changes the cells formatting and turns on word wrap. Word wrap is required for linebreaks to be shown in a cell. However if you return a string with a linebreak in it from a UDF Excel does not update the format.

I can think of two possible solutions:

  1. Manually enable word wrap on any cell you use this function in
  2. (Not recommended) Store the reference in Application.Caller during your ConcatenateRange UDF call, then set an Application.OnTime(now, "AddWordWrap") call and write the AddWordWrap subroutine so that it uses the stored reference to add the wordwrap formatting to the cell (this is because you cannot update the cell's format in a UDF). This method is buggy and problematic.
AndASM
  • 9,458
  • 1
  • 21
  • 33
  • Your additional information on word warp is spot on. This is a limitation of excel. I must live with it. – jherbold Jun 07 '20 at 06:20
0

Just use the CHAR(10) separator:

=ConcatenateRange(A1:A4;CHAR(10))
Thiago Lewin
  • 2,810
  • 14
  • 18
0

Use:

=A1&"[Alt+Enter]"&A2&"[Alt+Enter]"&A3&"[Alt+Enter]"&A4
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
0

try using this

Sheet1.Range("A1").Value = "sgar" & Chr(10) & "saha"
VMAtm
  • 27,943
  • 17
  • 79
  • 125
sagar mhatre
  • 9
  • 1
  • 3
0
Cells(row, column) = "current line" & Chr(10) & "new line"
ILya Kuzmin
  • 85
  • 1
  • 1
  • 9
-1

I stuck this in and it did work once I used 'wrap text'.

dra_red
  • 432
  • 1
  • 3
  • 10