C# Excel Interop Unable to get Characters.Text property when Range length is > 256

838 views Asked by At

I'm trying to Bold specific characters in an Excel sheet using C# Excel interop library. I have the specific characters within curly braces {} and using this function to make them bold.

void FormatCharacters(Range r)
{
    Characters chars = r.Characters[0, r.Text.Length];
    if (chars.Text.Contains("{") && chars.Text.Contains("}"))
    {
        int startIndex = chars.Text.IndexOf("{");
        int len = chars.Text.IndexOf("}") - startIndex + 1;
        Characters bold = r.Characters[startIndex, len];
        bold.Font.Bold = true;
        bold.Text = bold.Text.Replace("{", "");
        bold.Text = bold.Text.Replace("}", "");
    }
    else
        return;
    FormatCharacters(r);
}

The function works perfectly if the cell has text less than 256 characters. When the cell has text greater than 256, I get the following exception:

System.Runtime.InteropServices.COMException

Message=Unable to get the Text property of the Characters class

ErrorCode=-2146827284

How do I overcome this 256 character limit in Excel Characters interface?

Any alternative approaches using interop?

0

There are 0 answers