首页 > 解决方案 > 将数据从 Excel 发送到 Word 时可以设置页面大小和边距吗?

问题描述

我有如下代码:

Dim blnNewApp As Boolean
Dim wordApp As Object
Dim wordDoc As Object
Dim j As Long

Set wordApp = GetObject(, "Word.Application")

If wordApp Is Nothing Then
    Set wordApp = CreateObject("Word.Application")
    blnNewApp = True
End If

Set wordDoc = wordApp.Documents.Add()

With ThisWorkbook.Sheets(strSHEET_NAME)
    For j = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row

        strLineOfText = .Cells(j, "A").Text
    wordApp.Selection.TypeText strLineOfText
        wordApp.Selection.TypeParagraph

    Next j
End With

wordApp.Visible = True
AppActivate wordApp.Caption

如果我想在创建的 Word 文档中设置页面大小和边距,我该怎么做?

标签: vbams-word

解决方案


页面大小和边距是PageSetup对象的属性。请注意,这种信息通常可以通过录制宏来发现...

由于问题中的代码使用后期绑定,因此需要使用纸张尺寸的数值而不是枚举(wdPaperLetter例如),并且需要以points形式传递边距值。

我已经修改了问题中的代码来演示。此外,我还进行了额外的优化:

  • Work with the objects (espcially Range objects), rather than Selection (similar logic as avoiding ActiveCell and Activate in Excel - it's more accurate)
  • Use the Document object that's declared and
    Dim blnNewApp As Boolean
    Dim wordApp As Object   'Word.Application
    Dim wordDoc As Object   'Word.Document
    Dim wordRange as Object 'Word.Range
    Dim j As Long

    Set wordApp = GetObject(, "Word.Application")

    If wordApp Is Nothing Then
        Set wordApp = CreateObject("Word.Application")
        blnNewApp = True
    End If

    Set wordDoc = wordApp.Documents.Add()
    Set wordRange = wordDoc.Content

    With ThisWorkbook.Sheets(strSHEET_NAME)
        For j = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row

            strLineOfText = .Cells(j, "A").Text
            wordRange.Text = strLineOfText & vbCr  'vbCr = a new paragraph
            With wordDoc.PageSetup
              .PaperSize = 2 'wdPaperLetter
              .BottomMargin = 452 'CentimetersToPoints(1.5)
              .TopMargin = 700 'CentimetersToPoints(2)
              .LeftMargin = 680 'CentimetersToPoints(2)
              .RightMargin = 680 'CentimetersToPoints(2)
            End With
        Next j
    End With

    wordApp.Visible = True
    AppActivate wordApp.Caption

推荐阅读