如何遍历Excel中的每个列并根据条件应用列宽

时间:2013-07-18 01:26:26

标签: excel vba

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

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

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

1 个答案:

答案 0 :(得分: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宽度,而不是像素