Hi,
In our company, we open files a few times a day that need to be fixed by macro.
The macro is responsible for setting the optimal column width but it sets columns width only on one sheet at a time and need to be triggered by hotkey. Files have 4 sheets always.
My question for help: is it possible to run this macro on every sheet from the file - automatically when opening the files?
I would be so grateful for help, it would save us a lot of time.
We are using this macro:
Option Explicit
Function SetOptimalWidth(Optional oDummy As Variant) As String
Const MAX_WIDTH = 10000
Dim oCurrentController As Variant
Dim oActiveSheet As Variant
Dim oCursor As Variant
Dim oColumns As Variant
Dim oColumn As Variant
Dim i As Long
Rem First of all, we find out the active sheet
oCurrentController = ThisComponent.getCurrentController()
oActiveSheet = oCurrentController.getActiveSheet()
Rem In order not to change all the columns on the sheet, we find the UsedRange
oCursor = oActiveSheet.createCursor()
oCursor.gotoEndOfUsedArea(True)
oColumns = oCursor.getColumns()
Rem Now we optimize the width of each column in a given range
For i = oColumns.getCount() - 1 To 0 Step -1
oColumn = oColumns.getByIndex(i)
oColumn.OptimalWidth = True
Rem We could stop at this
Rem But some columns may become so wide that they won’t fit on the screen
Rem In this example, we will limit the maximum width to 10 cm
If oColumn.Width > MAX_WIDTH Then
oColumn.OptimalWidth = False
oColumn.Width = MAX_WIDTH
EndIf
Next i
SetOptimalWidth = "Clear this cell if you want to stop the automatic column width"
End Function