根据第 1 行中的列名自动调整 Excel 列宽

Auto Fit Excel Column Width based on Column Names in Row 1

即使只为包含列名称的第一行选择了范围,下面的代码也会根据其中的数据自动调整列。

让我们考虑 Sheet 具有所需 Sheet 的句柄。我希望自动调整从 C 到 F 的列。

Sheet.Range("C1:F1").Columns.AutoFit

参考:https://msdn.microsoft.com/en-us/library/office/ff820840.aspx

我希望看到完整的列名,而无需手动调整大小。

将单元格值和格式从 C1:F1 复制到右侧未使用的列并使用 Range.AutoFit 。使用调整后的宽度设置原来的列宽。

Dim c As Long, cc As Long
With Worksheets("Sheet1")
    cc = .Cells(1, .Columns.Count).End(xlToLeft).Column + 1
    For c = 3 To 6
        .Cells(1, c).Copy Destination:=.Cells(1, cc)
        .Columns(cc).AutoFit
        .Columns(c).ColumnWidth = .Columns(cc).ColumnWidth
    Next c
    .Columns(cc).Cells.Clear
End With

这将仅根据格式化的 header 行调整每个列宽。