View Single Post
  #6   Report Post  
Posted to microsoft.public.excel.misc
Ken Johnson
 
Posts: n/a
Default Excel should merge cells without removing content of any cell

Hi Rumpa,
First I have to correct myself. I was saying that when cells are merged
in Excel all but the top-left cell have their values hidden, not
deleted. I now see that those cell values are deleted, not just hidden.
This means that those cell values will not reappear if after merging
you then go FormatCellsAlignment, then remove the tick from Merge
cells. However, if instead of back-tracking to remove the tick you
click on Undo (or Control + Z) those cell values reappear. This is a
special case that only works when done immediately after applying the
cell merging.

I have put together a macro that I think, and hope, will merge cells in
Excel the way you have described the way Word merges cells.

Test the macro out on a backup copy of your file first (changes the
macro makes cannot be undone, unless you close your file without
saving).

First select the range of cells that you want merged , then run the
macro.
The code places each selected cell value into the selection's
top-left cell. Column values are separated by a single space. Row
values are separated by a line break (same as Alt + Enter). Those cells
are then merged.

It works quite well when merging rows from one column. Merging columns
is not so good visually. I don't know of an easy way of lining up the
different column values within an Excel cell. Excel cells, unlike Word
cells, do not have a tab that could be used to line up the
corresponding column values from the different rows.

Public Sub MergeLikeWord()
Application.ScreenUpdating = False
Dim iRows As Long
Dim iColumns As Long
Dim vaMergeArray As Variant
Dim I As Long, J As Long
Dim stDisplayedText As String
Dim stMergeColumns() As String
vaMergeArray = Selection
iRows = Selection.Rows.Count
iColumns = Selection.Columns.Count
If iRows = 1 And iColumns = 1 Then Exit Sub
ReDim stMergeColumns(1 To iRows)
For I = 1 To iRows
For J = 1 To iColumns
stMergeColumns(I) = stMergeColumns(I) _
& vaMergeArray(I, J) _
& IIf(J < iColumns, Space(1), "")
Next J
Next I
For I = 1 To iRows
stDisplayedText = stDisplayedText _
& stMergeColumns(I) _
& IIf(I < iRows, Chr(10), "")
Next I
With ActiveCell
.Value = stDisplayedText
.VerticalAlignment = xlTop
End With
Application.DisplayAlerts = False
With Selection
.Merge
.Rows.AutoFit
End With
Application.DisplayAlerts = True
End Sub

I hope this helps you solve your problem.
Happy New Year (1hour 17minutes to go)

Ken Johnson