简体   繁体   English

使用Excel VBA编写Word文档标题

[英]Writing in a Word Document Header Using Excel VBA

I'm creating a button in an excel sheet that generates a report in Word. 我在Excel工作表中创建一个按钮,该按钮在Word中生成报告。 So far, so good except I'm trying to have a header in the document that looks like this: 到目前为止,一切都很好,除了我试图在文档中添加一个类似于以下内容的标题: 在此处输入图片说明

but it ends up just looking like this: 但最终看起来像这样: 在此处输入图片说明

where it just comes up as this weird extra window at the bottom of my document and it says page 3, when there is only two pages of the document (or there only should be two pages) my code is: 它刚好出现在文档底部的这个怪异的额外窗口中,显示为第3页,当文档只有两页时(或者应该只有两页),我的代码是:

'Header

  With Wordapp
   .activeDocument.Bookmarks("Header").Select
   .Selection.TypeText Text:="CFD Analysis of Antenna EPA "
   .Selection.MoveRight Count:=1
   .Selection.TypeText Text:=today
   .Selection.MoveRight Count:=1
   .Selection.TypeText Text:=antennamanu & " " & modnum
  End With

The behavior shown in the screen shot of the question is due to use the Select method. 问题的屏幕快照中显示的行为是由于使用Select方法引起的。 This separate Header pane, in the Draft view, comes from the days of Word 2.0, where WYSIWYG wasn't available for headers, footers, comments and similar things. 在草稿视图中,此单独的页眉窗格来自Word 2.0的时代,在该版本中,所见即所得不适用于页眉,页脚,注释和类似内容。

Instead of using Select , working directly with Range objects will avoid the problem. 不用使用Select ,而是直接使用Range对象可以避免此问题。 The code in the question can be altered along these lines: 问题中的代码可以按照以下方式更改:

'Header
  Dim rngHeader as Word.Range 'or Object if this is late-binding
  With Wordapp
   Set rngHeader = .ActiveDocument.Bookmarks("Header").Range
   rngHeader.Text ="CFD Analysis of Antenna EPA " & vbTab & _
                    today & vbCr & antennamanu & " " & modnum
  End With

In the original code, the document apparently has a TAB and a Paragraph character. 在原始代码中,文档显然具有TAB和段落字符。 So Selection.MoveRight is moving to the tab stop, and then to the next paragraph. 因此Selection.MoveRight移至制表位,然后移至下一段。 The above code writes those as it goes, so these characters should be removed from the report template being used. 上面的代码按原样编写了这些代码,因此应从所使用的报告模板中删除这些字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM