我尚未对此进行彻底的测试,但它一直为我工作。本质上,它将自动调整所有图纸,然后返回并设置列宽为原始宽度,除非已通过自动调整对其进行了扩展。我只有10列,但从来没有超过1000行,因此请根据需要调整代码。
Sub ResizeCells()
Dim sheetCounter As Integer
Dim rowCounter As Integer
Dim colCounter As Integer
Dim totalWidth As Double
Dim oldColWidths(1 To 10) As Double
For sheetCounter = 1 To ThisWorkbook.Sheets.Count
ActiveWorkbook.Worksheets(sheetCounter).Select
totalWidth = 0
' Extend the columns out to 200
For colCounter = 1 To 10
oldColWidths(colCounter) = Cells(1, colCounter).ColumnWidth
totalWidth = totalWidth + oldColWidths(colCounter)
Cells(1, colCounter).ColumnWidth = 200
Next
For rowCounter = 4 To 1000
If Cells(rowCounter, 1).Value <> "" Or Cells(rowCounter, 2).Value <> "" Or Cells(rowCounter, 3).Value <> "" Then
Rows(rowCounter & ":" & rowCounter).EntireRow.AutoFit
End If
Next
' do autofit
For colCounter = 1 To 10
Cells(1, colCounter).EntireColumn.AutoFit
Next
' reset to original values if current width is less than the original width.
For colCounter = 1 To 10
If Cells(1, colCounter).ColumnWidth < oldColWidths(colCounter) + 0.25 Then
Cells(1, colCounter).ColumnWidth = oldColWidths(colCounter)
End If
Next
Next
End Sub