c# comparing style objects in MS Word

佐手、 提交于 2019-12-11 05:31:52

问题


I have to edit all headings inside a word document.

I tried this:

Word.WdBuiltinStyle[] styleArray = {
    Word.WdBuiltinStyle.wdStyleHeading1,
    Word.WdBuiltinStyle.wdStyleHeading2,
    Word.WdBuiltinStyle.wdStyleHeading3,
    Word.WdBuiltinStyle.wdStyleHeading4,
    Word.WdBuiltinStyle.wdStyleHeading5,
    Word.WdBuiltinStyle.wdStyleHeading6,
    Word.WdBuiltinStyle.wdStyleHeading7,
    Word.WdBuiltinStyle.wdStyleHeading8,
    Word.WdBuiltinStyle.wdStyleHeading9
  };

  foreach (Word.Paragraph paragraph in Globals.ThisAddIn.Application.ActiveDocument.Paragraphs)
  {
    if (styleArray.Any(a => a.Equals((Word.WdBuiltinStyle)paragraph.Range.get_Style())))
    {
      paragraph.Range.Font.Size = size;
      paragraph.Range.Font.Name = font;
    }
  }

But it says I can't cast and I#m feeling this is not a very good way to do it.

It also doesn't work with

if (styleArray.Contains(paragraph.Range.get_Style()))

Any help on this please?


回答1:


There's a difference between the built-in style enumeration and an actual style. That's why the comparison isn't working. The array needs to be an array of styles. For example:

Word.Document doc = Globals.ThisAddin.Application.ActiveDocument;
enter code here
Word.Style[] styleArray = {
  doc.Styles(Word.WdBuiltinStyle.wdStyleHeading1),
  doc.Styles(Word.WdBuiltinStyle.wdStyleHeading2),
  doc.Styles(Word.WdBuiltinStyle.wdStyleHeading3) //and so on
};


来源:https://stackoverflow.com/questions/53628979/c-sharp-comparing-style-objects-in-ms-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!