AutoFit Merged Cell Row Height

AutoFit Merged Cell Row Height

You’ve most likely heard this warning — “Avoid merged cells in your Excel worksheets!”, and that is excellent advice. Merged cells can cause problems, especially when they’re in a table that you’ll be sorting and filtering. You’ll run into more problems if you try to autofit merged cell row height.

Forced to Merge

Occasionally though, you might have no choice but to use one or more merged cells on a worksheet. As long as you avoid merging table cells, and proceed with caution, things might be okay.

In the example shown below, there is an order form, and space for a note about the order. If the note will always be short, there’s no need to merge the cells – just let the text flow across the columns.

mergecellsautofit01

However, if the notes will be two or more lines, you’ll need to merge the cells, and turn on Wrap Text. Adjusting the column width would affect the product list that starts in row 12, so that’s not an option.

Merged Cell Row Height

Usually, if you add more text to a single cell, and Wrap Text is turned on, the row height automatically adjusts, to fit the text.

When the cells are merged in row 10, the row height has to be manually adjusted when the text changes. That works well, as long as you remember to do it, but it can be a nuisance, if the text changes frequently.

And if you forget to adjust the row height, you might print the order form, while key instructions are hidden.

mergecellsautofit02

AutoFit Merged Cell Row Height

To fix the worksheet, so the merged cells adjust automatically, you can add event code to the worksheet.

[Update: The original code is below, and there are several modified versions of the code in the comments. There is also an updated version of Smallman’s code in this December 2015 blog post.]

The merged cells are named OrderNote, and that name will be referenced in the event code.

mergecellsautofit03

Code to AutoFit Merged Cell Row Height

We want the row height to adjust if the OrderNote range is changed, so we’ll add code to the Worksheet_Change event.

The code that I use is based on an old Excel newsgroup example, that was posted by Excel MVP, Jim Rech.

Note: As Jeff Weir pointed out in the comments below, this code will wipe out the Undo stack, so you won’t be able to undo any steps you’ve previously taken. So, instead of using the Worksheet_Change event, you could use the workbook’s BeforePrint event, to reduce the Undo problem.

  1. Right-click on the sheet tab, and paste the following code on the worksheet module. Note: Only one Worksheet_Change event is allowed in each worksheet module.
  2. Change the range name from “OrderNote”, to the named range on your worksheet.
  3. If your worksheet is protected, you can add code to unprotect and protect the worksheet.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim MergeWidth As Single
Dim cM As Range
Dim AutoFitRng As Range
Dim CWidth As Double
Dim NewRowHt As Double
Dim str01 As String
str01 = "OrderNote"
  If Not Intersect(Target, Range(str01)) Is Nothing Then
    Application.ScreenUpdating = False
    On Error Resume Next
    Set AutoFitRng = Range(Range(str01).MergeArea.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 = MergeWidth
      .EntireRow.AutoFit
      NewRowHt = .RowHeight
      .Cells(1).ColumnWidth = CWidth
      .MergeCells = True
      .RowHeight = NewRowHt
    End With
    Application.ScreenUpdating = True
  End If
End Sub

How It Works

The event code checks to see if the changed cell is in the OrderNote range. If it is, the code runs, and does the following:

  1. Unmerge the cells
  2. Get the width of the first column in the OrderNote range
  3. Get the total width for all columns in the OrderNote range
  4. Add a little extra to the calculated width
  5. Set the first column to the calculated total width
  6. Autofit the row, based on the note next in the first column
  7. Get the new row height
  8. Change the first column to its original width
  9. Merge the cells
  10. Set the row height to the new height

Screen updating is turned off while the code runs, and it all happens in the blink of an eye.

Test the Event Code

To test the code, make a change to the text in the named merged cells, then press Enter. The row height should adjust automatically.

Is this code, to AutoFit merged cell row height, something that you’ll use in your workbooks? Please let me know in the comments.
__________________

135 thoughts on “AutoFit Merged Cell Row Height”

  1. Hi Olivia
    There is no email address as I requested. I can send you the coding from my reply with the code running smoothly. There is a problem at your end. It will be something simple like you are putting the coding in the incorrect place.
    If you simply dump the code in a fresh file, make sure you put it in worksheet 1 module (if you want it to run on sheet1) it should be OK. That is all I will do and it will run like a dream.
    Take care
    Smallman

  2. Hello! I was able to get the row height to adjust when entering text for one cell in the sheet code (str01 = “E40” or “E42” or “E44”), but when I enter a named range (from Name Manager) in the formula (str01 = “OrderNote”) (OrderNote = E40 E42 E44) none of the cells in the named range will adjust row height. Any ideas?
    Thanks!

  3. Hi Jordan
    Have a look at the post by suzi above. There is use of this method with named ranges. If you can not make anything from the thread then email me your file. I will have a look at it later in the week when I get back from my travels.
    Take care
    Smallman

  4. Hello Smallman
    I am able to get merged cells row height autofit when merged have its text but if merged cells contain link from another sheet none of the cells autofit automatically. I have merged cells in bill sheet row 10 & coulumn C10, D10 are merged cells that have cell link from “bill data” B5. I required to automatically autofit the row height as i update the sheet “bill data”. I am new to excel and dont know vba codes very much. Plzzzzzzzz help?????

  5. Hi Debra/Smallman
    I just wanted to say thank you for all the work you’ve put into this! I know I’m posting quite late (I can see this was opened in 2012, talk about late to the party) but it has helped me so much on my latest project!
    The main issue I have had with this project is that the merged cells do not follow any sort of pattern. They are user generated from a web form – eg. When a user inputs new information under a sub-heading the extract updates with more merged cells. These cells will vary from sheet to sheet so I needed it to be dynamic as possible. That being said, if anyone else is having the same issue I have posted a very slightly tweaked code below.
    The only issue I have left now is that I seem to be getting a white gap inside the re-merged cell using the code below, but when I used Debra’s & Smallman’s code I wasn’t. Are either of you able to help at all? If you can that would be amazing! If not, I’d just like to say thanks again for all the work you’ve put into this!

    Sub FindAllMerged()
    Dim c As Range
    Dim sMsg As String
    Dim mw As Single
    Dim cw As Double
    Dim rwht As Double
    Dim rng As Range
    For Each c In ActiveSheet.UsedRange
        If c.MergeCells Then
     c.Select
    With c
          .MergeCells = False
          cw = .Cells(1).ColumnWidth
          mw = 0
          For Each cM In c
              cM.WrapText = True
              mw = cM.ColumnWidth + mw
          Next
          mw = mw + c.Cells.Count * 0.66
          .Cells(1).ColumnWidth = mw
          .EntireRow.AutoFit
          rwht = .RowHeight
          .Cells(1).ColumnWidth = cw
            With Selection
            .MergeCells = True
            End With
          .RowHeight = rwht
        End With
        End If
    Next
    End Sub
    

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.