Home » excel » c# – Accessing CustomProperties on Worksheet with Name

c# – Accessing CustomProperties on Worksheet with Name

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m trying to access a custom property on a worksheet by using the name of the property, but it seems this is not supported (at least not in C#, I saw others reporting that it works in VB and documentation also says so). Can someone confirm that this is not working in C#? Here is example code:

activeWorkSheet.CustomProperties.Add("Test", 123);
// Accessing by index works, but by name it doesn't. 
// The documentation says access by name should be possible
var works = activeWorkSheet.CustomProperties.Item[1].Value;
var doenstWork = activeWorkSheet.CustomProperties.Item["Test"].Value;

I know that a workaround is just some method that iterates over all the properties and finds the right one, but I would really like to avoid any additional overhead.

How to&Answers:

Can someone confirm that this is not working in C#?

Just tried with Office 2013 preview and version 15 of the Interop API, and I can confirm that this does not work in C# (throws a COMException with the message of “Type mismatch”).

I have checked the documentation, which states that it should be perfectly legal to use the key name as index for the Item indexer – from the docs for the CustomProperties.Item property, it states that the following indexer is available:

CustomProperty this[
    Object Index
] { get; }

… and in the following text, the docs states:

Parameters

Index

Type: System.Object

Required Object. The name or index number of the object.

… so since the documentation states that the name is a valid key, the behavior we experience might likely be a bug.