首先,您需要考虑几个事实:
- 如果您想“为某些行指定属性“Autofit”和最小高度。”那么你应该先使用自动拟合,然后在
for each 循环中使用Max 函数而不是Min。像这样:
Sub sheetFormat()
Dim sn As Integer, formatRng As Range, minHeight
sn = ThisWorkbook.Sheets.Count 'To format the last worksheet in this workbook
Set formatRng = ThisWorkbook.Sheets(sn).Range("B4:H50")
minHeight = 30 'or 50
formatRng.WrapText = True
formatRng.Rows.AutoFit
Dim Rng As Range
For Each Rng In formatRng
Rng.RowHeight = Application.WorksheetFunction.Max(Rng.RowHeight, minHeight)
Next Rng
End Sub
该代码将按照您的要求执行,但前提是您在用内容填充单元格后格式化工作表。如果 - 在调用此 SUB 之后 - 您使用不适合 minHeight 点行高的字符填充 formatRng 内的单元格,则此代码将不会 AutoFit 行高。它只会根据此规则格式化已经有内容的单元格:
(formatRng 范围内的所有单元格的最小行高为minHeight,内容不适合此minHeight 的单元格具有更大的行高,由AutoFit 决定。
- 例如,当您明确将行高指定为
Range.RowHeight 为 30 时,您是在告诉 excel 不要调整高度以实现最佳拟合(即,您正在禁用 .AutoFit 功能) ,并且不会自动将高度调大。没有办法做到这一点。
这意味着您需要将行高设置为隐式调整(通过选择 AutoFit 作为行高来完成),并且如果您愿意,可以通过某种方式使其不低于 minheight解决1.中的问题,避免显式调整行高。
这可以通过将formatRng中每一行中的单元格的字体大小变大来实现,因此这些行中的高度会变大达到minheight,然后当我们在这些行中使用autofit时行,它将使“默认行高”——即使是空白单元格——不低于minheight。
通过反复试验,我发现 40 pt Arial 字体使行高为 50,这是实现此目的的 vba 代码:
Sub sheetFormat()
Dim sn As Integer, formatRng As Range
sn = ThisWorkbook.Sheets.Count 'To format the last worksheet in this workbook
Set formatRng = ThisWorkbook.Sheets(sn).Range("B4:H50")
Dim p As Integer, q As Integer, lastColStr As String
p = formatRng.Row 'first row of the range
q = formatRng.Rows.Count + p - 1 'last row of the range
lastColStr = Mid(Cells(1, Columns.Count).Address, 2, 3) 'Last column Name (XFD on my machine)
' Making Cells in the range "XFD4:XFD50" have 40pt Arial font
With ThisWorkbook.Sheets(sn).Range(lastColStr & p & ":" & lastColStr & q)
.Font.Name = "Arial"
.Font.Size = 40
End With
formatRng.WrapText = True
formatRng.VerticalAlignment = xlCenter 'I added this one just to see the whole contents of the cell
formatRng.Rows.AutoFit
End Sub
有关此技巧的详细信息:
https://excelribbon.tips.net/T005663_Changing_Default_Row_Height.html