如何循环遍历Excel中的每一列并根据条件应用列宽
我需要excel vba代码,默认情况下自动调整所有列,然后循环遍历每个列宽,如果任何宽度超过特定值(例如50),则将该特定列宽限制为30,并将word wrap设置为true如何循环遍历Excel中的每一列并根据条件应用列宽,excel,vba,Excel,Vba,我需要excel vba代码,默认情况下自动调整所有列,然后循环遍历每个列宽,如果任何宽度超过特定值(例如50),则将该特定列宽限制为30,并将word wrap设置为true Public Function LastColumn(Optional wks As Worksheet) As Long If wks Is Nothing Then: Set wks = ActiveSheet LastColumn = Cells.Find("*", SearchOrder:=xlB
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
有没有更好的方法来实现这一点
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宽度,而不是像素记录宏,然后编辑宏。如果在遵循@chancea的建议后仍然存在问题,请显示代码以提高响应的几率。宏记录器将向您显示要使用的对象和方法。你必须付出至少这么多的努力:)在你获得这些信息之后,只需根据你的需求设置条件逻辑。他发布的代码是宏记录器代码。宏记录器无法解决循环部分。请注意,他有
AutoFit
、WrapText
和ColumnWidth
。我要说的是,他已经尽了最小的努力,代码是功能性的。所需的只是使用UsedRange.Columns对象(您无法从宏记录器中获得)