【发布时间】:2018-11-20 14:27:12
【问题描述】:
我有运行以下代码的 Excel 工作簿。我在 Word 文档中已经有徽标和页码,所以我不需要从 Excel 中粘贴整个范围。我有两个文本框,应该插入电子表格中的数据。
我需要复制
Worksheets("Other Data").Range("A58:A60")并将其粘贴到 Word 文档标题中的“文本框 1”。三个句子在不同的行上。文本框应该换行吗?我需要复制
Worksheets("Other Data").Range("A68")并将其粘贴到 Word 文档标题中的“文本框 2”。一句。AutoFitWindows 不起作用。必须有一些带有变量的东西,但我无法弄清楚到底是什么问题。尝试了不同的方法,但没有成功。
这是我的代码:
Sub excelToWord_click()
Dim head As Excel.Range
Dim foot As Excel.Range
Dim WordTable As Word.Table
Set wdApp = CreateObject("Word.Application")
wdApp.Documents.Open FileName:=ThisWorkbook.Path & "\" & "MyDOC" & ".docx"
wdApp.Visible = True
Set head = ThisWorkbook.Worksheets("Other Data").Range("A58:A60")
head.Copy
'|| I need to paste copied cells to "Text Box 1" in my Word document ||'
With wdApp.ActiveDocument.Sections(1)
.Headers(wdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Shapes("Text Box 1").Activate
head.Paste
End With
'|| ---------------------------------------------------------------- ||'
Set head2 = ThisWorkbook.Worksheets("Other Data").Range("A68")
head2.Copy
'|| I need to paste copied cells to "Text Box 2" in my Word document ||'
With wdApp.ActiveDocument.Sections(1)
.Headers(wdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Shapes("Text Box 2").Activate
head2.Paste
End With
'|| ---------------------------------------------------------------- ||'
Set foot = ThisWorkbook.Worksheets("Other Data").Range("A62:H65")
foot.Copy
With wdApp.ActiveDocument.Sections(1)
.Footers(wdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Paste
End With
'|| Autofit table to page in Footer ||'
WordTable.AutoFitBehavior (wdAutoFitWindow)
'|| ---------------------------------------------------------------- ||'
'restore Word
If wdApp.ActiveWindow.View.SplitSpecial <> 0 Then
wdApp.ActiveWindow.Panes(2).Close
End If
If wdApp.ActiveWindow.ActivePane.View.Type = 1 _
Or wdApp.ActiveWindow.ActivePane.View.Type = 2 Then
wdApp.ActiveWindow.ActivePane.View.Type = 3
End If
wdApp.WordBasic.AcceptAllChangesInDoc
'wdApp.ActiveDocument.PrintOut, Copies:=1
wdApp.ActiveDocument.ExportAsFixedFormat outputfilename:=ThisWorkbook.Path & "\" & Sheets("MAIN").Range("D14").Value & ", " & Sheets("MAIN").Range("D11").Value & "_" & "Document" & "_" & ".pdf", exportformat:=wdExportFormatPDF
wdApp.ActiveDocument.SaveAs ThisWorkbook.Path & "\" & Worksheets("MAIN").Range("D14").Value & ", " & Worksheets("MAIN").Range("D11").Value & "_" & "Document" & "_" & ".docx"
wdApp.Quit '<--| quit Word
Set wdApp = Nothing '<--| release object variable
'wdApp.ActiveWindow.Close savechanges:=False
End Sub
【问题讨论】:
-
我建议激活
Option Explicit:在 VBA 编辑器中转到 Tools › Options › Require Variable Declaration你会立即看到你的问题。 -
@PEH 感谢您的编辑。
-
@user7202022 检查是否启用了语法检查也很有帮助。在 VB IDE 中转到 Tools.Options.Editor 并确保选中代码设置窗格中的所有复选框。有些人对 Auto syntax 复选框的必要性持怀疑态度,因为它可能很烦人,但它是一个起点。如果它让您烦恼,请稍后将其关闭。