如何解决如何使用VBA自动调整列宽?
Sub RowHeightMin()
Dim finalRow As Integer
Dim i As Integer
finalRow = Cells(Rows.Count,1).End(xlUp).Row
Range("A1:A" & finalRow).EntireRow.AutoFit
For i = 2 To finalRow
If Range("A" & i).EntireRow.RowHeight < 27 Then
Range("A" & i).EntireRow.RowHeight = 27
End If
Next i
End Sub
我以此为例进行行自动调整,但是就像它的列对应项一样。
自动调整将基于它的B行单元格。
谢谢。
解决方法
尝试以下示例代码,它将使用Rows(2)
设置所有列的宽度。
Sheets("Sheet1").Rows(2).Columns.AutoFit
#Edit
下面的代码将AutoFit
设置为行和列的范围,然后,如果行数小于27到27,则重新调整行的大小。ThisWorkbook
是宏的保存位置。如果不是“ Sheet1”,则需要将工作表名称更改为您的工作表名称。如果您不喜欢使用SpecialCells(xlLastCell)
,则可以随时定义lastrow,lastcol变量。
Sub AutofitRange()
With ThisWorkbook.Sheets("Sheet1") 'Define the workbook and worksheet
'Assign the rng varaible using .Cells.SpecialCells(xlLastCell)
Dim rng As Range: Set rng = .Range("A1").Resize(.Cells.SpecialCells(xlLastCell).Row,.Cells.SpecialCells(xlLastCell).Column)
With rng
.Rows.AutoFit 'Autofit the rows in the range
.Rows(2).Columns.AutoFit 'AutoFit the columns in the range based on Row 2
'Resize the rows in col 1 if less then 27
If Columns(1).Rows.EntireRow.RowHeight < 27 Then Columns(1).Rows.RowHeight = 27
.WrapText = False
End With
End With
End Sub
,
假设OP想要自动拟合所有列,但是可以很容易地更改。
Sub ColWidthMin()
Const MinimalWidth As Double = 12.56
With Sheet1 ' using the sheet's Code(Name)
Dim lastCol As Long
lastCol = .Cells(1,.Columns.Count).End(xlToLeft).Column
Dim rng As Range
Set rng = Range(.Cells(1,1),.Cells(1,lastCol))
'autofit columns
rng.EntireColumn.AutoFit
Dim i As Long
For i = 1 To rng.Columns.Count
If rng.Columns(i).ColumnWidth < MinimalWidth Then
rng.Columns(i).ColumnWidth = MinimalWidth
End If
Next i
End With
End Sub
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。