VBA to AutoFit Row Height and AutoFit Column Width

dslhs

New Member
Joined
Apr 4, 2022
Messages
42
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

How to change case of text in Excel?
Use =UPPER() for upper case, =LOWER() for lower case, and =PROPER() for proper case. PROPER won't capitalize second c in Mccartney

Forum statistics

Threads
1,215,094
Messages
6,123,071
Members
449,092
Latest member
ipruravindra

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