views:

321

answers:

2

Basically I would like to keep the existing format of an Excel cell. If I use ActiveCell.Value2 = "new value";

The ActiveCell displays "new value" but loses the user defined formatting ( say red font, blue background), all formatting values goes back to Excel default format values.

Note: If you replace a cell value using Excel, Excel keeps the user's format. When recording this action as a macro, Excel uses the property FormulaR1C1 but according to MSDN this a property used for macros.

A: 

You may want to copy the cell and "Paste" the formatting back - http://www.ozgrid.com/forum/showthread.php?t=56324

taspeotis
I will keep this idea in mind for another feature request that ai need to do, thank you for your help
mas_oz2k1
+1  A: 

If I use ActiveCell.Value2 = "new value" the ActiveCell displays "new value" but loses the user defined formatting

No, it does not, I just tested it (with Excel 2003). Opened a new empty document, formatted a column with some colors and user defined number format and and entered

ActiveCell.Value2="1"

in the immediate Window of the VBA editor. The existing format is kept intact. So if you have another scenario to deal with (where the format gets lost), please describe it in detail.

EDIT: if this behaviour is really different in VSTO, as a workaround, you can try to save the relevant format information of the ActiveCell before changing the value, for example

fci = ActiveCell.Range.Font.ColorIndex
ici = ActiveCell.Range.Interior.ColorIndex
pat = ActiveCell.Range.Interior.Pattern
nf = ActiveCell.Range.NumberFormat

then change the value

ActiveCell.Value2 = "new value"

and afterwards reassign the format info again

ActiveCell.Range.Font.ColorIndex = fci
ActiveCell.Range.Interior.ColorIndex = ici
ActiveCell.Range.Interior.Pattern = pat
ActiveCell.Range.NumberFormat = nf

(but beware, this is 'air code').

Doc Brown
I think the problem only occurs with using Excel through C# - in VBA it works fine. (The question is tagged C# and VSTO but doesn't actually mention it in the question :0)
ScottF
Sorry, I am using VSTO and C# and I found this behaviour annoying.This solution does not help because I need to render a report with multiple row and columns (100s)
mas_oz2k1
You were right, value2 does not change the formatting, there was range.clear call somewhere in the code that was clearing content and formatting.
mas_oz2k1