Question posted 2012 · +16 upvotes
I’m having a problem fromatting cells in an excel sheet. For some reason my code seems to be changing the style of all cells when I just want to change the style of a few specified, or a specified range.
Here’s some of the code that I am using:
app = new Microsoft.Office.Interop.Excel.Application();
workbook = app.Workbooks.Add(1);
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
//Change all cells' alignment to center
worksheet.Cells.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
//But then this line changes every cell style back to left alignment
worksheet.Cells[y + 1, x + 2].Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
Why would it change the style of multiple cells when I set it to just work on one? Is it not supposed to work how I want it to? Is there another way of doing this?
Accepted answer +14 upvotes
Based on this comment from the OP, “I found the problem. apparentlyworksheet.Cells[y + 1, x + 1].HorizontalAlignment”, I believe the real explanation is that all the cells start off sharing the same Style object. So if you change that style object, it changes all the cells that use it. But if you just change the cell’s alignment property directly, only that cell is affected.
Excel VBA objects referenced (5)
Application— Using events with the Application objectApplication— Working with Other ApplicationsCells.Style— PivotTable.ShowTableStyleLastColumn property (Excel)pivottable-showtablestylelastcolumn-property-excel-63370f64-5188-50fd-3e8a-6fdb0Interop.Excel— Using events with Excel objectsInterop.Excel— Using Excel worksheet functions in Visual Basic
Top excel Q&A (6)
- Shortcut to Apply a Formula to an Entire Column in Excel +335 (2011)
- How should I escape commas and speech marks in CSV files so they work in Excel? +136 (2012)
- Convert xlsx to csv in linux command line +96 (2012)
- How to create a link inside a cell using EPPlus +50 (2011)
- IF statement: how to leave cell blank if condition is false ("" does not work) +44 (2013)
- T-SQL: Export to new Excel file +44 (2012)
excel solutions on this site
.