So, today is my bad day
I discovered that excel row AutoFit - doesn't work
a = "Please"
b = "Do AutoFit"
range01.Value = a & vbNewLine & b
range01.EntireRow.AutoFit // First and last line are horizontally cutted
Chr(10) instead of vbNewLine - doesn't help
It works only if I write without line breaks:
range01.value = a & b
range01.EntireRow.AutoFit // works !!! Thanks to Microsoft !
Cause. In Excel, you cannot use the AutoFit feature on a column that contains a cell merged with cells in other columns. Likewise, you cannot use AutoFit on a row that contains a cell merged with cells in other rows.
Select the row or rows that you want to change. On the Home tab, in the Cells group, click Format. Under Cell Size, click AutoFit Row Height.
In the Number group, click on the dialog box launcher icon (the small tilted arrow icon at the bottom right of the group) In the Format cells dialog box that opens up, click on the 'Protection' tab. Uncheck the Locked option. Click OK.
If manual or automatic wrapping doesn't work in Excel, it may be because the selected cell is a merged cell. If you want to wrap text in this cell in Excel you must first unmerge the cells. If you want to keep the merged cell, you can still use the word wrap by manually adjusting the row height and column width.
Make sure that the cells that have line breaks in them have "Wrap Text" turned on. You can turn it on with VBA like so:
Sub test1()
Dim a As String, b As String
a = "Please"
b = "Do AutoFit"
Range("A1").Value = a & vbNewLine & b
Range("A1").WrapText = True
Range("A1").EntireRow.AutoFit
End Sub
Autofit doesn't work on merged cells. My guess is that's what you are trying to do.
Work around this by simulating the autofit on a single cell with the same width as your merged cell and set the height it gives you.
Something like this:
Dim YourString As String, a As String, b As String
Dim TempLoc as Range
a = "Please"
b = "Do AutoFit"
YourString = a & vbNewLine & b
Set TempLoc = range01.offset(0, 10) ' Given the column 10 columns to the right has the exact same witdh as your merged cell.
' Autofit a single cell to get correct height
With TempLoc
.Value = YourString
.WrapText = True
.EntireRow.AutoFit
.RowHeight = TempLoc.RowHeight
.ClearContents
End With
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With