Is .setColumnWidth() broken in Excel scripts?

Marco Couch 30 Reputation points
2024-09-13T16:51:01.04+00:00

I have written a very simple code in Office Scripts which should simply set some column widths and the header rows (see below). However, when I run the script, the column widths are nowhere near the values I have input (I have added comments to show the column widths which get set when the script is run).

Is this a general issue with .setColumnWidth() or have I missed something?

function main(workbook: ExcelScript.Workbook) {

	let sheets = workbook.getWorksheets();

	sheets.forEach(sheet => {
		sheet.getRange("E:G").getFormat().setColumnWidth(14.00); //becomes 2.00 (19px)
		sheet.getRange("H:I").getFormat().autofitColumns; 
		sheet.getRange("J:J").getFormat().setColumnWidth(25.00); //becomes 4.00 (33px)
		sheet.getRange("L:L").getFormat().setColumnWidth(16.43); //becomes 2.43 (22px)
		sheet.getRange("S:S").getFormat().setColumnWidth(11.43); //becomes 1.43 (15px)
		sheet.getRange("U:U").getFormat().setColumnWidth(19.29); //becomes 3.00 (26px)
		sheet.getRange("1:1").getFormat().autofitRows();
	})
}
Excel
Excel
A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
1,985 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
4,023 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Michelle Ran 346 Reputation points Microsoft Employee
    2024-09-13T21:35:27.0866667+00:00

    Hi @Marco Couch - thanks for reaching out! I've confirmed that setColumnWidth() incorrectly sets the width and have flagged it for our team to investigate (internal tracking: #9333095). I'll follow up once I have more information to share. In the meantime, I believe the best workaround is to try a few different values in the API until you get the desired column width. Sorry that I don't have a better solution at the moment!


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.