Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel: how to autofit columns on startup?

Tags:

excel

vba

Is there a way to autofit all the columns in the opening sheet which contain data? I'm looking for a solution that is not depended on modifications on a certain excel file but which works on every excel file and runs on excel startup.

like image 440
jrara Avatar asked Dec 22 '11 10:12

jrara


1 Answers

You can use an object module that will receive an Application Event (see more info on Chip Pearson's website).

This is the code you have to copy-paste to the module ThisWorkbook of the file PERSONAL.XLSB:

Option Explicit

Private WithEvents App As Application

Private Sub Workbook_Open()
    Set App = Application
End Sub

Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
    'Statement to show that it works
    MsgBox "Opened Workbook: " & Wb.Name
    'Statement to autofit columns
    ActiveSheet.UsedRange.Columns.AutoFit
End Sub

You could also add a loop over the workbook sheets.

like image 53
JMax Avatar answered Sep 18 '22 04:09

JMax