8

所以,今天是我糟糕的一天
,我发现 excel 行 AutoFit - 不起作用

a = "Please"
b = "Do AutoFit"
range01.Value = a & vbNewLine & b  
range01.EntireRow.AutoFit // First and last line are horizontally cutted  

Chr(10) 而不是 vbNewLine - 无济于事
它只有在我没有换行符的情况下才有效:

range01.value = a & b
range01.EntireRow.AutoFit  //  works !!!  Thanks to Microsoft !
4

5 回答 5

15

确保其中有换行符的单元格已打开“换行文本”。您可以使用 VBA 将其打开,如下所示:

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
于 2012-08-26T19:54:43.297 回答
6

自动调整不适用于合并的单元格。我的猜测是这就是你想要做的。

通过在与合并单元格具有相同宽度的单个单元格上模拟自动调整并设置它为您提供的高度来解决此问题。

像这样的东西:

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
于 2013-08-27T17:54:09.600 回答
3

I solved an issue with this - I had a row with two merged cells both containing multi-line text with Chr(10) linefeeds - with Wrap set ON (but no lines actually wrap - only the Chr(10)s cause new lines). Autofit wouldn't work due to the merged cells.

The VBA workaround was to use a spare cell on the same row, and fill it with the same number of Chr(10) as found in one (either) of the multi-line cells. Then call AutoFit for that cell now containing the same number of invisible line feeds. Make sure the font and size are the same in the spare cell!

' make C36 spare cell contain the same number of Chr(10) as D36, using a Repeat function :
' (after counting Chr(10) by comparing the length before and after substituting Chr(10) with "")
Worksheets(1).Range("C36").Value = _
   Application.WorksheetFunction.Rept(Chr(10), _
     Len(Worksheets(1).Range("D36").Value) - Len(Replace(Worksheets(1).Range("D36").Value, Chr(10), "")))
Worksheets(1).Range("C36").Rows.AutoFit

An alternative method for other scenarios could be to use an extra, hidden, worksheet - set a single cell to the same column width as your merged cells, copy the contents over, call autofit (which should work on the unmerged cell), then use the resulting rowheight from that one.

于 2015-01-15T11:40:36.753 回答
3

你可以这样做:

Private Sub Worksheet_Activate()
Worksheets("Sheet1").Range("A:A").EntireRow.AutoFit
End Sub
于 2014-07-16T16:58:14.120 回答
0

一种解决方法是将导致自动调整问题的列的列宽缩小一点,选择要更改的所有行,通过双击行分隔符之一自动调整行高,最后自动调整通过双击列分隔符来获取第一步中的列。如果只有一列或几列始终在其单元格中包含最多的文本,则可能效果最佳。

于 2018-05-11T15:12:19.667 回答