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
    Cells.Select
    Cells.EntireColumn.AutoFit

'AutoFit One Column
    ThisWorkbook.Worksheets("Sheet1").Columns("O:O").EntireColumn.AutoFit
  
'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
    ThisWorkbook.Worksheets("Sheet1").Cells.EntireColumn.AutoFit

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


End Sub

No comments:

Post a Comment