VBA to AutoFit Row Height and AutoFit Column Width

dslhs

Board Regular
Joined
Apr 4, 2022
Messages
50
Office Version
  1. 2019
Platform
  1. Windows
Hello,

I'm pretty sure there is a simple solution to this, but I'm struggling.

I would like a VBA code that is triggered by a change to the contents of the cell A2.

When A2 is changed, it will automatically AutoFit Row Height and AutoFit Column Width for the cells W7:AE42.

VBA Code:
Private Sub Worksheet_Change(ByVal Target As Range)    
' Check if the changed cell is B2
If Target.Address = "$B$2" Then        
Application.EnableEvents = False                '
Range("W7:AE42").Rows.AutoFit        
Range("W7:AE42").Columns.AutoFit                
' Re-enable events        
Application.EnableEvents = True    
End IfEnd Sub

I thought this would work, but alas it hasn't.

Any help would be much appreciated.
 
I am about to log off, so if it is just a Data Validation drop down, try copying in the code below. It shouldn't make any difference.
If it still doesn't work then show us the picture I asked for in the previous post and advise on what type of drop down it is.

VBA Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    ' Check if the changed cell is A2
    If Not Intersect(Target, Range("A2")) Is Nothing Then
        Application.EnableEvents = False                '
        Range("W7:AE42").Rows.AutoFit
        Range("W7:AE42").Columns.AutoFit
        ' Re-enable events
        Application.EnableEvents = True
    End If
End Sub
 
Upvote 0

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.

Forum statistics

Threads
1,224,823
Messages
6,181,177
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top