首页 > 解决方案 > MS Word InsertBreak 抛出异常

问题描述

尝试使用参数(例如 wdPageBreak 或 wdLineBreak)通过 Range 插入中断时出现错误“类型不匹配”。但是没关系,InsertBreak 无参数。我是唯一一个得到这种行为的人,还是另一个 Word API 错误?

//MS Word VBA Reference
Set myRange = ActiveDocument.Paragraphs(2).Range 
With myRange 
 .Collapse Direction:=wdCollapseEnd 
 .InsertBreak Type:=wdPageBreak 
End With

//c++ code
HRESULT hr = pWordDoc->GetParagraphs()->Item(1)->GetRange()->
        InsertBreak(&variant_t(Word::wdPageBreak));  //hr = 0x80020005 TypeMismatch
hr = pWordDoc->GetParagraphs()->Item(1)->GetRange()->
            InsertBreak(&vtMissing);                 // hr = S_OK

标签: c++vbams-wordms-office

解决方案


如果无法让这部分 Word 对象模型的 C++ 版本正常运行,您可以通过使用 ANSI 字符代码插入某些类型的中断来解决它。(它们也可用于搜索/识别文档文本中的中断。)

Page break:      ANSI 12 (= press Ctrl+Enter)
Line break:      ANSI 11 (= press Shift+Enter)
Paragraph break: ANSI 13 (= press Enter)

请注意,ANSI 12 也是各种分符类型的字符代码;分页符是默认设置,因此如果需要分页符,您可以插入 ANSI 代码。

为了插入分节符,可以使用该Sections.Add方法。这接受指示分节符在文档中的位置和类型的参数。方法签名:

expression.Add(Range, Start)

Whereexpression是一个代表 Sections 集合的变量。(wordDoc.Sections.Add例如)

的有效值Start来自WdSectionStart枚举:

wdSectionContinuous 0 Continuous section break. 
wdSectionEvenPage   3 Even pages section break. 
wdSectionNewColumn  1 New column section break. 
wdSectionNewPage    2 New page section break. 
wdSectionOddPage    4 Odd pages section break. 

推荐阅读