user158182
user158182

Reputation: 97

excel cell formatting

How can I change the cell format to be text in Excel programatically?

Upvotes: 2

Views: 8428

Answers (3)

Joon
Joon

Reputation: 2147

The way that I answer this and other excel queries it to record a macro in Excel, perform the action that I want to see how to do, and then look at the macro to see what it recorded.

Doing that, this questions answer is:

Selection.NumberFormat = "@"

Upvotes: 4

Hassen
Hassen

Reputation: 870

To apply a style to a named range

Create a new style and set its attributes.

Excel.Style style = Globals.ThisWorkbook.Styles.Add("NewStyle", missing);

style.Font.Name = "Verdana";
style.Font.Size = 12;
style.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
style.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Gray);
style.Interior.Pattern = Excel.XlPattern.xlPatternSolid;

Create a NamedRange control, assign text to it, and then apply the new style.

Microsoft.Office.Tools.Excel.NamedRange rangeStyles = this.Controls.AddNamedRange(this.Range["A1", missing], "rangeStyles");

rangeStyles.Value2 = "'Style Test";
rangeStyles.Style = "NewStyle";
rangeStyles.Columns.AutoFit();

Upvotes: 0

butterchicken
butterchicken

Reputation: 13883

You can use:

Range("A1").NumberFormat = "@"

for text

Range("A1").NumberFormat = "dd/mm/yyyy hh:mm:ss" 

for a date.

Range("A1").NumberFormat = "#,###"

for money, etc.

Upvotes: 6

Related Questions