tags:

views:

81

answers:

3

Need to get a value of an enumeration of a given string literal like "xlCenter" (these values are cut and pasted from Excel Macro). I would like to retrieve the actual constant value (int) -4108="xLCenter" via com marshaling is this possible ? if so how ?

Ideally I am looking for function like this

public int ExcelConstant(string constantName)
{ ...} 

Thanks

+2  A: 

In Visual Studio you should add a reference to Excel in your project. You will find Excel in the COM tab of the Add Reference dialog. The name is Microsoft Excel 12.0 Object Library (or a slightly different name if you are using another version of Excel).

In your project you are then able to use types in the Microsoft.Office namespaces. For instance you would probably want to use the Microsoft.Office.Interop.Excel.Constants.xlCenter enumeration constant. If you need the numerical value you simply cast it to an integer:

Int32 xlCenterValue = (Int32) Microsoft.Office.Interop.Excel.Constants.xlCenter;

Or you could create a function as you have outlined in your question:

public Int32 ExcelConstant(String constantName) {
  return Enum.Parse(
    typeof(Microsoft.Office.Interop.Excel.Constants),
    constantName
  );
}

If you want to call the Excel automation API from managed code you probably don't care about the numerical values of the enumerations. Instead you should use the enumeration directly in your code:

var worksheet = (Worksheet) excel.ActiveWorkbook.ActiveSheet;
var cell = (Range) worksheet.Cells[1, 1];
cell.HorizontalAlignment = Constants.xlCenter;
Martin Liversage
+1. You might want to emphasize that the cast is the important part of getting the enum value into an integer.
Hans Passant
A: 

I'm not sure if this is the exact answer you want but I suggest taking a look at Microsoft.Office.Interop.Excel.Constants:

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.constants%28office.11%29.aspx

ho1
+1  A: 

you may use Enum.GetValues

Alex Pacurar