Delphi Code - Autofit Entire Row and Column in Excel Worksheet
Here is a simple Delphi procedure that opens an existing Microsoft Excel file and autofits Columns A through E in the first worksheet (i.e., tab). The file is saved using the same name (overwrites the original file). Performing the autofit function on an entire row adjusts the height of the row to achieve the best fit for the row contents. Similarly, performing the autofit function on an entire column adjusts the width of the column to achieve the best fit for the column contents. The most relevant parts of the code are highlighted. Comments are included to explain the code. If you copy and paste the code into your program, be sure to change the form and procedure names to match your setup. For additional Excel automation solutions, see Microsoft Excel Automation with Delphi.
— share —
procedure TForm1.AutofitEntireRowAndColumnInExcelWorksheet(Sender: TObject); var ExcelFileName: String; ExcelApplication, ExcelWorkbook, ExcelWorksheet: Variant; begin //be sure ComObj and Variants units are included in the "uses" clause
ExcelFileName := 'C:\PhysiologyWeb\delphi_code_examples\excel_file.xlsx'; //replace file name with the name of your file
try //create Excel OLE ExcelApplication := CreateOleObject('Excel.Application'); except ExcelApplication := Null; //add error/exception handling code as desired end;
If VarIsNull(ExcelApplication) = False then begin try ExcelApplication.Visible := True; //set to False if you do not want to see the activity in the background ExcelApplication.DisplayAlerts := False; //ensures message dialogs do not interrupt the flow of your automation process. May be helpful to set to True during testing and debugging.
If VarIsNull(ExcelWorkbook) = False then begin //connect to Excel Worksheet using either the ExcelApplication or ExcelWorkbook handle try ExcelWorksheet := ExcelWorkbook.WorkSheets[1]; //[1] specifies the first worksheet except ExcelWorksheet := Null; //add error/exception handling code as desired end;
If VarIsNull(ExcelWorksheet) = False then begin ExcelWorksheet.Select;
ExcelWorksheet.Columns[1].EntireColumn.AutoFit; //autofits Column A ExcelWorksheet.Columns[2].EntireColumn.AutoFit; //autofits Column B ExcelWorksheet.Columns[3].EntireColumn.AutoFit; //autofits Column C ExcelWorksheet.Columns[4].EntireColumn.AutoFit; //autofits Column D ExcelWorksheet.Columns[5].EntireColumn.AutoFit; //autofits Column E //reference //https://docs.microsoft.com/en-us/office/vba/api/excel.range.autofit