通过vba复制wordheader会增加换行符

时间:2013-07-30 20:35:14

标签: vba ms-word word-vba

我有以下VBA宏删除word文档的标题,然后打印文档然后添加标题。标题基本上只是一个图像。

问题是每次执行宏时,标题中都会添加换行符,这会在执行一些操作后将主要部分移动。

这是我的代码:

Sub print()
    Dim oSec As Section
    Dim oHead As HeaderFooter

    For Each oSec In ActiveDocument.Sections
        For Each oHead In oSec.Headers
            If oHead.Exists Then oHead.Range.CopyAsPicture
                oHead.Range.Delete
        Next oHead
    Next oSec

    ActivePrinter = "Bullzip PDF Printer"

    Application.PrintOut FileName:="", Range:=wdPrintAllDocument, Item:= _
        wdPrintDocumentWithMarkup, Copies:=1, Pages:="", PageType:= _
        wdPrintAllPages, Collate:=True, Background:=True, PrintToFile:=False, _
        PrintZoomColumn:=0, PrintZoomRow:=0, PrintZoomPaperWidth:=0, _
        PrintZoomPaperHeight:=0

    For Each oSec In ActiveDocument.Sections
        For Each oHead In oSec.Headers
            If oHead.Exists Then oHead.Range.Paste
        Next oHead
    Next oSec

End Sub

有人可以解释为什么每次运行宏时都会添加额外的行吗?

2 个答案:

答案 0 :(得分:0)

我能想到的最快的想法(可能不是最优雅的)是删除粘贴图像后出现的附加段落。我认为额外的段落是最后一段。因此,您的第二个循环将如下所示:

'...beginning of your code here
For Each oSec In ActiveDocument.Sections
    For Each oHead In oSec.Headers
        If oHead.Exists Then oHead.Range.Paste
            'new line to delete additional paragraph
            oHead.Range.Paragraphs(oHead.Range.Paragraphs.Count).Range.Delete
    Next oHead
Next oSec
'...rest of your code here

答案 1 :(得分:0)

我刚遇到与页脚类似的问题。每次我添加一些东西(文字,在我的情况下),都会添加一个回车符。以下是我要解决的问题:

currentFooter = ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text
If Right(currentFooter, 1) = vbCr Then
    newFooter = Left(currentFooter, Len(currentFooter) - 1)
End If
'then you make the changes you need to the truncated footer value and apply it back
    ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text = newFooter