Macros

AutoFit Merged Cell Heights

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