Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the CodeName for Worksheet in Excel using VSTO

Tags:

excel

vsto

I did like this:

if (Excel._Application.ActiveWorkbook != null)
{
    List<WorksheetKeyValue> sheets = new List<WorksheetKeyValue>();
    foreach (object ws in ExcelApp.ActiveWorkbook.Worksheets)
    {
        string strCodeName = ws.CodeName
    }
}

but strCodeName is an empty string when it supposed to be Sheet1, Sheet2, ..., SheetN like in VBA.

Thanks

like image 827
Ramesh Shrestha Avatar asked Feb 25 '23 17:02

Ramesh Shrestha


2 Answers

In your condition, you can use Worksheet.CustomProperties as alternative to hold unique property of the sheet.

Worksheet ws = **current_sheet** as Worksheet;
ws.CustomProperties.Add("SheetID", **some_value**);

So, later on you can access them as

foreach (Excel.CustomProperty prop in ws.CustomProperties)
{
    if (prop.Name == "SheetID")
    {
       // access as prop.Value and prop.Name
    }
 }

Hope this helps.

like image 98
Santoo Avatar answered Mar 03 '23 15:03

Santoo


In VSTO, the CodeName property is an infra-structure property that you should not be using from your code.

From MSDN:

This property supports the Visual Studio Tools for Office infrastructure and is not intended to be used directly from your code.

Tell us what you are trying to accomplish, maybe there is an alternative way to do what you want.

Also, I noted from your code that you are using an Excel Addin. You can try to check if the CodeName property returns what you expect if you use an Excel Document Customization instead of an Excel Addin.

Update: In order for you to uniquely tag a worksheet you could use a GUID and set it as a custom property of the worksheet using Worksheet.CustomProperties.

like image 22
João Angelo Avatar answered Mar 03 '23 15:03

João Angelo