行高AutoFit不起作用

时间:2012-08-26 18:21:10

标签: excel vba

所以,今天是我糟糕的一天 我发现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 个答案:

答案 0 :(得分:11)

确保其中包含换行符的单元格已打开“自动换行”。您可以像这样使用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

答案 1 :(得分:3)

自动调整对合并的单元格不起作用。我的猜测就是你要做的事情。

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

这样的事情:

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

答案 2 :(得分:2)

你可以这样做:

Private Sub Worksheet_Activate()
Worksheets("Sheet1").Range("A:A").EntireRow.AutoFit
End Sub

答案 3 :(得分:1)

我解决了这个问题 - 我有一行有两个合并的单元格都包含带有Chr(10)换行符的多行文本 - Wrap设置为ON(但没有行实际换行 - 只有Chr(10)的原因新线)。由于合并的单元格,自动调整不起作用。

VBA解决方法是在同一行上使用备用单元,并使用与多行单元中的一个(任一个)中找到的相同数量的Chr(10)填充它。然后为该单元格调用AutoFit,该单元格现在包含相同数量的不可见换行符。 确保备用单元格中的字体和大小相同!

' 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

其他方案的另一种方法可能是使用额外的隐藏工作表 - 将单个单元格设置为与合并单元格相同的列宽,复制内容,调用自动调整(应该在未合并的单元格上工作) ,然后使用该结果的行高度。

相关问题