在Excel中使用宏在Word文档中插入分页符

问题描述 投票:0回答:1

我正在尝试让我的宏在 Word 中制作三个表格。它目前制作了一张大表并正确格式化它,但我找不到如何在所需的时间强制分页。我发现一个在 Word 中使用 vba 的宏,他们使用了 .InsertBreak,但这在我运行它时一直导致错误。

这是我目前的代码。它是从很多来源拼凑而成的,其中夹杂着我自己的一些东西;

Dim wdApp As New Word.Application
Dim wdDoc As Word.Document
Dim wdTbl As Word.Table
Dim xlSht As Worksheet
Dim lRow As Integer
Dim lCol As Integer
Dim r As Integer
Dim c As Integer
Dim Blanks As Integer
Dim First As Integer
Dim Second As Integer

lRow = Sheets("Feedback Sheets").Range("A1000").End(xlUp).Row - 2


Blanks = 0
i = 1
    Do While i <= lRow
    Set rRng = Worksheets("Feedback Sheets").Range("A" & i)

        If IsEmpty(rRng.Value) Then
        
            Blanks = Blanks + 1
            
                If Blanks = 1 Then First = i
                If Blanks = 2 Then Second = i
                
        End If
        
        i = i + 1
    Loop
'Now I know where end of each table is

Set xlSht = ActiveSheet: lCol = 5
With wdApp
  .Visible = True
  Set wdDoc = .Documents.Add
  With wdDoc
    Set wdTbl = .Tables.Add(Range:=.Range, NumRows:=2, NumColumns:=lCol)
    With wdTbl
      .Rows(1).Range.Font.Bold = True
      .Rows(1).HeadingFormat = True
      .Cell(1, 1).Range.Text = "Header 1"
      If lCol > 1 Then .Cell(1, 2).Range.Text = "Header 2"
      If lCol > 2 Then .Cell(1, 3).Range.Text = "Header 3"
    End With
    With xlSht
      For r = 1 To lRow
        If (r + 1) > wdTbl.Rows.Count Then wdTbl.Rows.Add
        If r = First Then wdDoc.InsertBreak

        If r = Second Then wdDoc.InsertBreak

        For c = 1 To lCol
          wdTbl.Cell(r + 1, c).Range.Text = xlSht.Cells(r, c).Text
        Next c
      Next r
    End With
  End With
End With

Set myTable = ActiveDocument.Tables(1)
With myTable.Borders
 .InsideLineStyle = wdLineStyleSingle
 .OutsideLineStyle = wdLineStyleDouble
End With

Set wdTbl = Nothing: Set wdDoc = Nothing: Set wdApp = Nothing: Set xlSht = Nothing

当我运行它时,我收到运行时错误“438”,对象不支持此属性或方法,并且调试突出显示此行;

If r = First Then wdDoc.InsertBreak

这就是为什么我认为问题出在 InsertBreak 上。

excel vba ms-word
1个回答
0
投票

wdDoc.InsertBreak
无效,如果您使用 IntelliSense,您就会知道,因为文档对象没有
InsertBreak
方法。

InsertBreak
Range
对象的方法。当您想要将中断符放置在您应该使用的表格之后之后:

wdDoc.Characters.Last.InsertBreak Type:=wdPageBreak
    
© www.soinside.com 2019 - 2024. All rights reserved.