Search code examples
c#excelevent-handlingstimulsoftnetoffice

Stimulsoft: Make Excel column auto width


I'm exporting a (Stimulsoft) report to excel but some cells text becomes long and causes horizontal alignment between cells to fail. It's clear word wraping enlarges cell height but don't spreads it to all others cells in same row.

I managed to make it more reliable setting CanGrow to false in all cells but that way user needs to manualy auto-fit columns width after excel opening.

There's any way to tell Excel to automatic fit all columns width?


Solution

  • There is, and it is rather simple.

    Private Sub AutoFitCols()
    
            Worksheets("Sheet1").Columns.AutoFit
    
    End Sub
    

    Just replace Sheet1 with the name of the worksheet you want the columns to autofit on.

    If you want this to happen automatically when the workbook is opened, you can place the code in the Workbook_Open event like so:

    Private Sub Workbook_Open()
    
            Worksheets("Sheet1").Columns.AutoFit
    
    End Sub
    

    Just be sure that code is within the ThisWorkbook code module.