andriscs

Hi,

I'm trying to create a Word document and I need a table of contents. I have different sized text and I tried to set their style according to the planned display. However, I get an exception when I try to call set_Style method. Why does that happen

Here is the code:

Code Block

object styleHeading2;object styleHeading3;




in the calling method:

Code Block

styleHeading2 = "Heading2";styleHeading3 = "Heading3";




in the called method:

Code Block

WordApp.Selection.Range.set_Style(ref styleHeading2); //here is the exception: the element doesn't exist




The error code is: 2146822454
I checked, none of the object were null, so I don't get it why the exception is thrown. Any idea






Re: Visual Studio Tools for Office WordApp.Selection.Range.set_Style throws exception

Ji Zhou – MSFT

Hi,

It results from that word cannot find the specified element. I record a macro in the Word and find that the string stands for Heading 2 is “Heading 2”, not “Heading2”. There should be a space between Heading and 2.

Codes below works:

Code Block

object styleHeading2; object styleHeading3;

styleHeading2 = "Heading 2"; styleHeading3 = "Heading 3";

app.Selection.Range.set_Style(ref styleHeading2);

Thanks

Ji






Re: Visual Studio Tools for Office WordApp.Selection.Range.set_Style throws exception

andriscs

Well, I modified the code and tried these ways:

Code Block

styleHeading2 = "Heading 2";
styleHeading3 = "Heading 3";



First way:

Code Block

WordApp.Selection.TypeText("Test text.");
WordApp.Selection.Range.set_Style(ref styleHeading2); //still throws an exception



Second way:

Code Block

WordApp.Selection.TypeText("Test text.");

object o1 = doc.Sentences[1].Start;
object o2 = doc.Sentences[1].End;
Range range = doc.Range(ref o1, ref o2);
range.set_Style(ref styleHeading3);




Both threw an exception of not founding the element.What else could I do





Re: Visual Studio Tools for Office WordApp.Selection.Range.set_Style throws exception

andriscs

I think I found the solution: the string is culture specific, I had to use the corresponding word in Hungarian (my language) intstead of "Heading" and then the element has been found. Thanks for the hints.