Skip to main content
 首页 » 编程设计

c#之无法从 C# 设置 Word 样式的基本样式

2024年02月13日13mfryf

Microsoft.Office.Interop.Word version 14.0.0.0. .NET 4.0 VS 2010.

MS Word API 的 Style 类有一个 BaseStyle 属性,可用于设置样式的基础(基于)样式。该属性在 VBA 中对我来说很好用。

但是,从使用 Word interopt 的 C# 中,没有 BaseStyle 属性。但是,有两个(据我所知未记录)函数 set_BaseStyle() 和 get_BaseStyle()。

当我调用 set_BaseStyle() 时,我收到一个 COMException 消息:

"This command is not available."

我认为这意味着COM接口(interface)不支持程序(命令)。但为什么?为什么会出现在intellisense中并编译?有解决方法吗?

请您参考如下方法:

这个简单的例子适用于我的机器(VS 2012,Office 2007)

        Application application = new Application {Visible = true}; 
 
        string styleName1 = "Heading 1"; 
        object styleNameObject1 = styleName1; 
 
        string styleName2 = "Heading 2"; 
        object styleNameObject2 = styleName2; 
 
        var document = application.Documents.Add(); 
        document.Select(); 
 
        application.Selection.set_Style(ref styleNameObject2); 
        Style style = (Style)application.Selection.get_Style(); 
        Style baseStyle = style.get_BaseStyle(); 
        style.set_BaseStyle(ref styleNameObject1); 
 
        application.Selection.Range.Text = "This is the title"; 
        application.Quit(false); 

所以问题可能出在您的设置上。该消息相当含糊,它说 word cannot do stuff,有关其他示例,请查看 C# and Word2010 : DeleteAllComments throws "This command is not available."或 search and replace in Word documents via .NET automation .

文件是只读的吗?其他样式或更简单的文件(例如我的示例)是否会发生这种情况? Word 中是否允许使用宏?