Skip to content

Instantly share code, notes, and snippets.

@airstrike
Created June 22, 2015 17:08
Show Gist options
  • Save airstrike/c0f0ed5c3af61b1e3f28 to your computer and use it in GitHub Desktop.
Save airstrike/c0f0ed5c3af61b1e3f28 to your computer and use it in GitHub Desktop.
Type StoreRangeInfo
'TODO: Store workbook name, file name.
Columns() As Variant
Widths() As Variant
End Type
Public AutoFitUndoData As StoreRangeInfo
Private Sub PrepareAutoFitUndo(Rng As Range)
ReDim AutoFitUndoData.Columns(1 To Rng.Columns.Count)
ReDim AutoFitUndoData.Widths(1 To Rng.Columns.Count)
Dim x As Long
x = 1
For x = 1 To Rng.Columns.Count
AutoFitUndoData.Columns(x) = Rng.Columns(x).Column
AutoFitUndoData.Widths(x) = Rng.Columns(x).ColumnWidth
Next
End Sub
Sub AutoFit()
If TypeName(Selection) <> "Range" Then Exit Sub
Dim SU As Boolean
Dim Sht As Worksheet
Set Sht = ActiveSheet
With Application
Call PrepareAutoFitUndo(Selection)
SU = .ScreenUpdating
.ScreenUpdating = False
With Selection
.EntireColumn.AutoFit
End With
If Selection.Columns.Count > 1 Then
Dim x As Long, max As Long
For x = 1 To Selection.Columns.Count
If Selection.Columns(x).ColumnWidth > max Then _
max = Selection.Columns(x).ColumnWidth
Next
Dim r As Range
For x = 1 To Selection.Columns.Count
Set r = Selection.Columns(x)
r.ColumnWidth = max
Next
Application.ScreenUpdating = SU
End If
End With
Application.OnUndo "Undo the AutoFit macro", "AutoFitUndo"
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment