AutoFit Merged Cell Heights
Excel's AutoFit doesn't work on merged cells. This macro sets the row height of merged cells so all of the wrapped text shows, which is ideal for notes to financial statements built in Excel.
- Select the merged cells and run it.
- Where a merge spans several rows, empty rows are removed and you're told about any rows it kept because they contain data.
This macro uses Turn Stuff Off/On, so add those two to the same module first.
VBA: AutoFit Merged Cell Heights
Sub Auto_Fit()
Dim DelY As New Collection, DelN As New Collection, RowDel As Range, RowKeep As Range
If MidSub <> vbYes Then Call TurnStuffOff
For Each Cell In Selection
If Cell.Value = "" Then GoTo Next_Cell
If Cell.Address = Cell.MergeArea.Address Then GoTo Next_Cell
If Cell.MergeArea.Rows.Count > 1 Then
yB = Cell.Row + 1: yE = Cell.Row - 1 + Cell.MergeArea.Rows.Count
For y = yB To yE
If Application.WorksheetFunction.CountA(Rows(y)) = 0 Then DelY.Add y Else DelN.Add y
Next y
End If
Set AutoFitRng = Range(Cell.MergeArea.Rows(1).Address)
With AutoFitRng
.MergeCells = False
CWidth = .Cells(1).ColumnWidth
MergeWidth = 0
For Each cM In AutoFitRng
cM.WrapText = True
MergeWidth = cM.ColumnWidth + MergeWidth
Next
'Small adjustment to temporary width
MergeWidth = MergeWidth + AutoFitRng.Cells.Count * 0.66
.Cells(1).ColumnWidth = Application.Min(MergeWidth, 255)
.EntireRow.AutoFit
NewRowHt = .RowHeight
.Cells(1).ColumnWidth = CWidth
.MergeCells = True
.RowHeight = NewRowHt
End With
Next_Cell:
Next Cell
If DelY.Count > 1 Then
For i = 1 To DelY.Count
If RowDel Is Nothing Then Set RowDel = Rows(DelY.Item(i)) Else Set RowDel = Union(RowDel, Rows(DelY.Item(i)))
Next i
RowDel.Delete
End If
If MidSub <> vbYes Then Call TurnStuffOn
If DelN.Count > 1 Then
For i = 1 To DelN.Count
If RowKeep Is Nothing Then Set RowKeep = Rows(DelN.Item(i)) Else Set RowKeep = Union(RowKeep, Rows(DelN.Item(i)))
Next i
RowKeep.Select
MsgBox "Please note that your initial selection included some multi-row merges. The macro has deleted those rows which were entirely empty but noted that some rows contained data and therefore weren't deleted. As a result the presentation of your workbook may not be as expected." & vbNewLine & vbNewLine & "Please review the highlighted rows (remembering that some data might be hidden) and move things around where necessary to ensure correct paragraph spacing.", vbCritical, "Multi-Row Merges Detected:"
End If
End Sub New to macros? Set up your Personal Macro Workbook first, then paste this code into its module.