I have a sub (on WorkSheet) which enlarge Column when I click on the Cell. The problem is I can’t back original size of the column when I leaving it.
I tried use some default parameters, but this end with error.
Then rngDEwidh.Columns.ColumnWidth = rngDEwidh.Columns.ColumnWidth
Then rngDEwidh.Columns.ColumnWidth = xlNone
Then rngDEwidh.Columns.ColumnWidth = ActiveCell.width
Here is a sub:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Static rngDEwidh As Range
If Not rngDEwidh Is Nothing Then rngDEwidh.Columns.ColumnWidth = xlNone
Set rngDEwidh = Target
rngDEwidh.Columns.ColumnWidth = 25
End Sub
Error when using xlNone and its ok if I use any value (10 for instance). But I need original size of the column.
The problem is I can’t back original size of the column when I leaving it.
Is this what you are trying?. This stores the previous width and column number in a variable.
Dim prevWidth As Long
Dim prevCol As Long
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If prevWidth <> 0 And prevCol <> 0 Then
Columns(prevCol).ColumnWidth = prevWidth
End If
On Error Resume Next
prevWidth = Target.ColumnWidth
prevCol = Target.Column
Columns(prevCol).EntireColumn.AutoFit
On Error GoTo 0
End Sub
Answer:
Here is a simple example where I sacrifice the TOP two rows that holds width for active and inactive columns:
You can obviously pick any row, maybe even use a named range in case you add/delete rows. But this is the code I used:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim rng As Range
For Each cl In Range("A1:E1")
Set rng = Intersect(cl.EntireColumn, Target.Columns)
If Not rng Is Nothing Then
cl.ColumnWidth = cl(1)
Else
cl.ColumnWidth = cl(2)
End If
Next cl
End Sub
EDIT
Another interesting thing to do is to create a Dictionary
upon activating the specific sheet. Fill that dictionary with the columnwidth of each column in the specified range. The rest is a small adaptation of the code I showed above.
Public dict As New Scripting.Dictionary
Dim rng As Range, cl As Range
Option Explicit
Private Sub Worksheet_Activate()
For Each cl In Range("A1:E1")
dict.Add cl.Column, cl.ColumnWidth
Next cl
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
For Each cl In Range("A1:E1")
Set rng = Intersect(cl.EntireColumn, Target.Columns)
If Not rng Is Nothing Then
cl.EntireColumn.AutoFit
Else
cl.ColumnWidth = dict(cl.Column)
End If
Next cl
End Sub
Tags: excelexcel