vba - 将数据从 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 文档中设置页面大小和边距,我该怎么做?
解决方案
页面大小和边距是PageSetup
对象的属性。请注意,这种信息通常可以通过录制宏来发现...
由于问题中的代码使用后期绑定,因此需要使用纸张尺寸的数值而不是枚举(wdPaperLetter
例如),并且需要以points形式传递边距值。
我已经修改了问题中的代码来演示。此外,我还进行了额外的优化:
- Work with the objects (espcially
Range
objects), rather thanSelection
(similar logic as avoidingActiveCell
andActivate
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
推荐阅读
- python - Discord.py:Guild.members 只返回当前机器人
- c - 使用 CMake(或 Visual Studio Code 中的 CMake 工具)自动查找依赖项并创建 CMakeLists.txt
- python - 将数据框列中的列表拆分为单独的列
- python-3.x - Python Openpyxl计划用字符串替换时间戳范围
- sql - 通过将一列设为两列(或简单地将一列拆分为两列)来加入表以获取输出
- python - 无法使用 pytesseract.image_to_string 从图像中读取文本
- wordpress - WordPress主题中的背景链接
- apache-spark - 从 kafka 的 spark 结构化流源写入 elasticsearch 时出现问题
- json - “crbug/1173575,非 JS 模块文件已弃用”颤振中的错误
- javascript - 收到错误内容安全策略错误:拒绝创建工作人员