在 VBA 中,我想格式化整个工作簿中的列以自动调整数据,但最大宽度为 50 或 75(对于哪个宽度没有偏好,50 或 75 只是建议)。我想这样做是因为我的一些字段可能有很长的值,而且我不想让滚动工作簿变得困难。我不想只添加最大宽度,因为我希望自动调整小于该宽度的单元格。
我有使用 VBA 代码中的循环自动调整列的代码,但不知道如何添加最大宽度条件。
我到目前为止的代码如下:
Dim sht As Worksheet
Sheets("Index").Select
On Error Resume Next
For Each sht In ThisWorkbook.Worksheets
sht.Cells.SpecialCells(xlCellTypeVisible).EntireColumn.AutoFit
Next sht
On Error GoTo 0
没有错误消息,代码运行良好。但是,我需要添加最大宽度条件,我不确定如何。
最佳答案
您可能需要遍历使用的列以一次更改其宽度:
Sheets("Index").Select
On Error Resume Next
For Each sht In ThisWorkbook.Worksheets
sht.Cells.SpecialCells(xlCellTypeVisible).EntireColumn.AutoFit
For c = sht.UsedRange.Column To sht.UsedRange.SpecialCells(xlCellTypeLastCell).Column
If sht.Cells(1, c).ColumnWidth > 75 Then sht.Cells(1, c).ColumnWidth = 75
Next c
Next sht
On Error GoTo 0
关于excel - 具有最大宽度条件的自动调整列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56653710/