0

我需要默认自动调整所有列的excel vba代码,然后循环遍历每个列的宽度,如果任何宽度超过特定值,例如50,则将该特定列的宽度限制为30并将自动换行设置为true。

Public Function LastColumn(Optional wks As Worksheet) As Long
    If wks Is Nothing Then: Set wks = ActiveSheet
    LastColumn = Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
End Function


Sub Macro1()
    Dim LastCol As Long
    Cells.Select
    Cells.EntireColumn.AutoFit
    LastCol = LastColumn(ThisWorkbook.Sheets("Sheet1"))
    For i = 1 To LastCol
        If Columns(i).ColumnWidth > 70 Then
            Columns(i).ColumnWidth = 70
            Columns(i).WrapText = True
        End If
    Next i
End Sub

有没有更好的方法来实现这一目标?

4

1 回答 1

0

就像是

Sub Autofit()

    Dim col As Range
    For Each col In ActiveSheet.UsedRange.Columns 'Only columns that actually have values
        col.Autofit
        If col.ColumnWidth > 50 Then 'Set your values here
            col.ColumnWidth = 30
            col.WrapText = True
        End If
    Next

End Sub

请注意,这使用 Excel 宽度,而不是像素

于 2013-07-19T02:40:14.293 回答