Yes. In PowerShell on Windows, use Excel’s COM automation to set a cell range’s HorizontalAlignment and, if needed, VerticalAlignment properties. For example, after selecting a range as $range, $range.HorizontalAlignment = -4108 centers its contents horizontally; Excel must be installed for this method.
How PowerShell changes Excel alignment
PowerShell does not format an Excel workbook by itself. It can ask the desktop Excel application to open a workbook and change its formatting through COM automation, which exposes Excel objects such as workbooks, worksheets, and ranges. The alignment setting belongs to a range, so the same command can format one cell, a block of cells, or an entire column.
For horizontal alignment, Excel uses numeric values for its built-in constants when accessed this way. The most useful values are:
-4108means center.-4131means left.-4152means right.1means General, Excel’s standard automatic alignment.
For vertical alignment, the common values are -4160 for top, -4108 for center, and -4107 for bottom. The number -4108 represents center in both the horizontal and vertical alignment properties. These are Excel constant values, not PowerShell keywords. COM automation does not always make Excel’s named constants available as convenient PowerShell names, so using the documented numeric values is a practical approach.
A complete Windows example
This example opens an existing workbook, centers the contents of cells A2 through D20 in both directions, turns on text wrapping, saves the workbook, and closes Excel. Change the file path and worksheet name to match your workbook. It assumes the file is not already open in a way that prevents editing.
$path = 'C:\Reports\Monthly.xlsx'
$excel = $null
$workbook = $null
$worksheet = $null
$range = $null
try {
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$workbook = $excel.Workbooks.Open($path)
$worksheet = $workbook.Worksheets.Item('Report')
$range = $worksheet.Range('A2:D20')
$range.HorizontalAlignment = -4108
$range.VerticalAlignment = -4108
$range.WrapText = $true
$workbook.Save()
}
finally {
if ($range -ne $null) {
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($range)
}
if ($worksheet -ne $null) {
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($worksheet)
}
if ($workbook -ne $null) {
$workbook.Close($false)
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook)
}
if ($excel -ne $null) {
$excel.Quit()
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel)
}
}
The script saves before closing, then closes the workbook with saving disabled because the changes have already been saved. The finally block runs even if a command fails, helping close Excel and release its COM objects rather than leaving an invisible Excel process running. For a critical workbook, first save a separate copy and test the script on that copy.
Choose the right range and alignment
The range string determines exactly which cells are changed. For a single cell, use a reference such as A1; for a rectangular block, use A2:D20. A worksheet column can be selected with B:B, and a row with 4:4. Applying formatting to an entire row or column can affect far more cells than intended, so use a bounded range when you know where the data ends.
To align text to the left, use $range.HorizontalAlignment = -4131. To align it to the right, use $range.HorizontalAlignment = -4152. To restore Excel’s usual automatic behavior, use $range.HorizontalAlignment = 1. Horizontal alignment does not change a cell’s value or convert text to a number; it only changes how the contents appear in the cell.
Vertical alignment is most noticeable when a row is taller than its contents, or when cells contain wrapped text. Setting VerticalAlignment to -4108 places contents in the vertical middle of the cell. For standard-height rows, top, center, and bottom may look similar, so check a row with increased height if you are verifying the effect.
Alignment is just one part of presentation. You can set related properties on the same range, such as WrapText to display long contents on multiple lines. Wrapping does not necessarily resize the row to show every line; if needed, use Excel’s row autofit feature or set row heights separately. Similarly, alignment does not merge cells, resize columns, or change the font.
Formatting multiple ranges or worksheets
If several nonadjacent blocks need the same format, you can set each range in turn. For example, create a range for a header and another for a totals block, then assign the same alignment property to each. Keeping the target ranges explicit is easier to review than formatting an entire worksheet without a clear reason.
To apply alignment across several worksheets, loop through the worksheet objects and set the range on each one. Confirm the sheet names or intended sheets first: a workbook can contain hidden sheets, and a mistaken loop can change more tabs than expected. If only certain sheets should be changed, check each sheet’s name before applying the formatting rather than assuming every worksheet has the same layout.
For recurring reports, it is often simpler to define the target range and desired alignment near the top of the script as variables. That makes it easier to adapt the script each month and reduces the chance of changing a hard-coded reference in several places. If the data area changes size, determine its actual last row or use a table-based range instead of relying on a fixed endpoint such as row 20.
Common problems and how to fix them
- Excel cannot be created: The COM example requires the Windows desktop version of Excel to be installed and registered. Installing PowerShell alone, or having only Excel for the web, is not enough. Check that Excel opens normally on the same computer.
- The worksheet is not found: The name passed to
Worksheets.Item()must match the worksheet tab name, including spaces. Check the workbook and update the script to use the correct name. - The file is read-only or locked: A workbook opened read-only cannot be saved over its original file. Check its file permissions and whether another process has it locked. If necessary, save a new copy rather than overwriting the source.
- The alignment appears unchanged: Verify the range reference and inspect a cell in that range. The selected cells might be empty, the workbook may not have been saved, or another later formatting step may have replaced the alignment.
- Excel remains running: A script that creates COM objects should close Excel and release the objects it created. Keep the cleanup code, and avoid using
Stop-Processon every Excel process: that can terminate a separate Excel session and lose unsaved work. - Text seems clipped: Alignment does not make a column wider. Adjust the column width, enable wrapping, or use the appropriate autofit command if the goal is to show more of the cell contents.
COM automation, alternatives, and platform limits
COM automation is useful when a script needs Excel’s own formatting behavior and can run on a Windows computer with desktop Excel installed. It is not a cross-platform Excel editing method. Excel for the web does not expose this desktop COM interface, and PowerShell on macOS cannot use Windows Excel COM automation. On Mac, use Excel’s interface or an approach designed for that platform instead of expecting New-Object -ComObject Excel.Application to work.
For command-line workbooks where desktop Excel is unavailable, a PowerShell module such as ImportExcel can read and write many spreadsheet features without launching Excel. Module capabilities and supported formatting options depend on the module version, so check its current documentation for the specific alignment feature before building a workflow around it. This is a different route from COM: it does not control the Excel application, and it may not reproduce every behavior of Excel itself.
Another possibility is to edit an .xlsx file as an Open XML package. That can suit specialized automation, but an .xlsx file is a structured collection of XML parts rather than a simple text file, and modifying styles correctly requires understanding the workbook’s style references. For a straightforward alignment change, COM or a well-documented spreadsheet module is generally easier to maintain.
Safety and reliable automation practices
Formatting commands can change a workbook permanently once saved. Before running a script against important data, make a backup and verify the file path, sheet name, and cell range. Consider opening the workbook visibly during initial troubleshooting by setting $excel.Visible = $true; once the result is confirmed, you can run it invisibly for routine automation.
Be deliberate about saving. The example calls $workbook.Save(), which writes changes back to the opened file if it is writable. If you want to preserve the source, use Excel’s SaveAs method to create a new workbook path, taking care to choose the correct file format and avoid overwriting an existing file unintentionally. Do not assume that closing Excel will save your changes: save explicitly, and decide what should happen if an error occurs before the save command.
COM automation is most appropriate for scripts that run in a normal interactive Windows session. Excel may display prompts or behave differently when started in restricted, unattended, or server environments. Test the complete process in the environment where it will run, and include logging or error handling if the script is part of a scheduled job. The cleanup pattern is important, but it does not remove the need to check whether the workbook actually saved successfully.
Frequently Asked Questions
How do I center text in an Excel cell with PowerShell?
Get the cell or range through Excel COM, then set its HorizontalAlignment property to -4108. For example, after defining $range, use $range.HorizontalAlignment = -4108. Save the workbook to keep the change.
How do I left-align or right-align cells?
Set HorizontalAlignment to -4131 for left alignment or -4152 for right alignment. Apply the setting to the precise cell or range you want to format.
Can PowerShell align cells without Excel installed?
Not with the COM approach shown here; it depends on the Windows desktop Excel application. A spreadsheet module may offer file-based formatting without launching Excel, but verify that the module version supports the alignment you need.
Can I do this in Excel for the web or on a Mac?
The Excel COM method is for desktop Excel on Windows. Excel for the web does not provide that COM interface, and PowerShell on Mac cannot automate Windows Excel through COM. Use Excel’s available interface or a platform-compatible workbook library.
Does alignment change the cell’s value?
No. It changes the visual placement of the existing contents, not the underlying value or data type. Use a separate data-cleaning or conversion step if you need to change text into a number or otherwise alter the cell’s contents.
Related
- Mirror Image Flip in Excel: What Works and How
- Microsoft Excel Zoom Options: Change Worksheet View
- Microsoft Excel Zoom Out: Ways to Shrink the View
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Filter Table Multiple Criteria: Practical MethodsTo filter an Excel table by multiple criteria, use the filter arrows in its column headings: set criteria…
- Excel Text Expansion: AutoCorrect, Formulas, and MoreExcel has no single feature called “text expansion,” but you can make a short abbreviation expand as you…
- Excel Time Formulas: Calculate Overnight PM-to-AM HoursIf A2 contains a PM start time and B2 contains the following AM finish time, enter =MOD(B2-A2,1) to…
- Sort List in Excel Formula: SORT, SORTBY, and MoreTo sort a list with a formula in Microsoft Excel for Microsoft 365, use SORT: with values in…
- Excel Power Query Custom Column IF: M Formula GuideIn Excel Power Query, create an if/then/else condition in a custom column with an M expression such as…
- Replace an Excel Cell Value: Methods, Formulas, and TipsTo replace a value in one Excel cell, select the cell, type the new value, and press Enter;…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.