首页 > 解决方案 > 如何使用 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 行单元格。

先感谢您。

标签: excelvba

解决方案


试试这个示例代码,它将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

推荐阅读