Google Sheets Script to Resize Columns Guide
In this article
To resize columns automatically in Google Sheets using a script, you use the Apps Script setColumnWidth() method or the autoResizeColumn() method. This allows you to standardize the look of a professional report or ensure that long strings of data are fully visible without manual dragging, which is essential for sheets that are updated frequently via imports or API connections.
What You'll Need
- A Google account with access to Google Sheets.
- A spreadsheet containing the data you wish to format.
- Basic access to the Apps Script editor (built into Google Sheets).
- Knowledge of which columns need resizing (column indices start at 1).
Step-by-Step
- Open the Apps Script Editor: Open your Google Sheet. In the top menu, click on Extensions and then select Apps Script. This will open a new browser tab with the script editor. Note that menu labels may differ slightly depending on your account type or region.
- Clear the Default Code: You will see a default function called
myFunction(). Delete all the existing code in the editor window to start with a clean slate. - Choose Your Method: Decide if you want a fixed width (e.g., every column is exactly 100 pixels) or an automatic width (the column expands to fit the longest piece of text).
- Write the Fixed Width Script: If you want specific widths, copy and paste the following code:
function resizeColumnsFixed() { var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // setColumnWidth(columnPosition, widthInPixels) sheet.setColumnWidth(1, 150); // Column A sheet.setColumnWidth(2, 300); // Column B sheet.setColumnWidth(3, 100); // Column C }In this example, Column A is set to 150 pixels, Column B to 300, and Column C to 100. - Write the Auto-Resize Script: If you want the sheet to calculate the width based on content, use this code:
function autoResizeAllColumns() { var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var lastColumn = sheet.getLastColumn(); for (var i = 1; i <= lastColumn; i++) { sheet.autoResizeColumn(i); } }This script identifies the last column containing data and loops through every column from 1 to that number, applying the auto-resize function to each. - Save the Project: Click the disk icon (Save) in the toolbar or press
Ctrl + S(Windows) orCmd + S(Mac). Give your project a name, such as "Column Resizer". - Run the Script: In the toolbar, ensure the correct function name is selected in the dropdown menu next to the "Debug" button. Click Run.
- Authorize Permissions: Since this is your first time running the script, Google will prompt you for permission. Click Review Permissions, select your Google account, click Advanced, and then click Go to Column Resizer (unsafe). Finally, click Allow. This is a standard security procedure for scripts you write yourself.
- Verify the Results: Return to your Google Sheet tab. You should see the columns adjust instantly to the widths specified in your code.
Common Mistakes
One of the most frequent errors is using a 0-based index for columns. In many programming languages, lists start at 0, but Google Apps Script's setColumnWidth and autoResizeColumn methods use 1-based indexing. If you try to use sheet.setColumnWidth(0, 100), the script will throw an error because there is no column 0. Always start your count at 1 for Column A.
Another common mistake is attempting to run the script on a protected sheet or a range that is locked. If the sheet is protected and the user running the script does not have edit permissions for those specific cells, the script will fail with a permission error. Ensure the account executing the script has full edit access to the target sheet.
Users also often forget to define which sheet the script should act upon. Using getActiveSheet() works if the sheet is open and active, but if the script is triggered by a time-based event (a trigger), getActiveSheet() may not refer to the sheet you expect. In those cases, it is better to use getSheetByName("Sheet1") to explicitly target a specific tab.
Lastly, some users try to use autoResizeColumn() on columns that contain formulas resulting in extremely long strings or very large numbers. This can lead to columns that are wider than the screen, making the sheet difficult to navigate. In these instances, a fixed width with "Wrap Text" enabled is a better design choice than auto-resizing.
Tips
To make your script more efficient, you can combine column resizing with other formatting tasks. For example, you can add sheet.getRange("1:1").setFontWeight("bold") to the same function to bold your header row every time the columns are resized. This ensures a consistent professional look without needing to run multiple scripts.
If you have a massive dataset with hundreds of columns, running a loop with autoResizeColumn() can sometimes be slow. To optimize this, consider resizing only the columns that are actually modified by your data imports. Instead of looping through the entire sheet, specify the exact range of columns that need attention.
For a truly automated experience, you can set up an Installable Trigger. In the Apps Script editor, click the clock icon (Triggers) on the left sidebar. Click Add Trigger, select your resize function, and set the event source to "From spreadsheet" and the event type to "On edit" or "On change". This means every time data is added or changed, the columns will automatically adjust themselves without you having to click "Run".
If you want to resize a group of columns to the same width simultaneously, you can use a simple for loop. For example, to make columns 4 through 10 all 120 pixels wide, use: for (var i = 4; i <= 10; i++) { sheet.setColumnWidth(i, 120); }. This is much cleaner than writing seven individual lines of code.
Troubleshooting
If the script does not run and you see an error message like "Exception: The coordinates of the range are out of bounds," check your column indices. This usually happens when the script tries to resize a column that doesn't exist (e.g., trying to resize column 30 in a sheet that only has 26 columns). Use sheet.getLastColumn() to dynamically determine the limit of your loop.
If the script runs without errors but the columns do not change, verify that you are targeting the correct sheet. If you have multiple tabs, getActiveSheet() targets whichever one was open when the script started. If you are using a trigger, this can be unpredictable. Switch to SpreadsheetApp.getActiveSpreadsheet().getSheetByName("YourSheetName") to ensure the script is hitting the right target.
If you encounter a "Permission Denied" error after the initial authorization, check if the spreadsheet is shared with you as "Viewer" only. Scripts cannot modify the structure of a sheet if the user does not have "Editor" permissions. You must be an editor to change column widths via script.
If the autoResizeColumn() method isn't making the column wide enough, it may be because the content is being truncated by a cell format or a hidden character. Ensure that the cells are not set to "Clip" or "Wrap" in a way that interferes with how the script calculates the required width. Generally, auto-resize works best on standard text alignment.
Frequently Asked Questions
Can I resize columns based on a specific word in a cell?
Yes. You can write a script that loops through a row, checks if a cell contains a specific keyword using getValue().includes("keyword"), and then calls setColumnWidth() only for that specific column index.
Does autoResizeColumn work for merged cells?
Auto-resizing merged cells is inconsistent. Because a merged cell spans multiple columns, Google Sheets cannot easily determine which single column should expand to fit the text. It is recommended to avoid merged cells in data-heavy sheets where scripts are used for formatting.
Can I set the width in centimeters or inches?
No. Google Apps Script uses pixels for column widths. You will need to estimate the pixel count (e.g., 100 pixels is a standard narrow column, 300-400 is wide). There is no direct conversion to physical measurements because screen resolution varies.
Will this script slow down my spreadsheet?
Running the script manually has a negligible impact. However, if you set an "On Edit" trigger to resize every single column on every single keystroke, you may notice a lag in performance. To prevent this, use a custom menu button to trigger the resize only when needed.
Can I resize rows using a similar method?
Yes. You can use sheet.setRowHeight(rowPosition, heightInPixels). The logic is identical to the column width method, substituting the row index for the column index and height for width.
Is there a way to resize all columns to fit the screen?
Google Sheets does not have a "Fit to Screen" script command. You would need to calculate the total available screen width (which the script cannot see) and divide that by the number of columns. The best alternative is to use autoResizeColumn() and then manually adjust the zoom level of the browser.