On UrbanPro

View My Profile       Proud to be a Teacher       Write a Review  

Sunday, February 8, 2015

VBA Code to autofit columns in MS Excel

Use Below VBA Code to autofit the columns in MS Excel as per you requirement

Sub AutoFitColumns()
     Dim sht As Worksheet

'AutoFit all the Columns in active worksheet

'AutoFit One Column
'AutoFit Multiple Columns
    ThisWorkbook.Worksheets("Sheet1").Range("I:I,L:L").EntireColumn.AutoFit 'Columns I & L
    ThisWorkbook.Worksheets("Sheet1").Range("I:L").EntireColumn.AutoFit 'Columns I to L
'AutoFit All Columns on Worksheet

'AutoFit Every Worksheet Column in a Workbook
    For Each sht In ThisWorkbook.Worksheets
    Next sht

End Sub