VBA从Excel从一个Word文档复制到另一个Word文档
我有一个Excel工作表,可以打开一个空白Word文档作为“主控”和一个“临时”单独的Word文档。我试图移动到“母版”的末尾,复制整个“临时”并粘贴到“母版”,然后在“母版”上输入一个分页符。我在“.Selection.EndKey单位:=wdStory Extend:=wdMove”、“.Add.Content.Paste”和“.Selection.InsertBreak类型:=7”上遇到错误,我不确定原因。我将迭代多个“临时”文档,并将它们逐个添加到“主控”中,但在我能够完成从“临时”到“主控”的一轮基本复制粘贴之前,我不想移动到循环中。还有一个boomark替换子程序,我没有展示它来降低社区的复杂性,因此在“临时”文档上有“Fields.Update”VBA从Excel从一个Word文档复制到另一个Word文档,excel,vba,ms-word,Excel,Vba,Ms Word,我有一个Excel工作表,可以打开一个空白Word文档作为“主控”和一个“临时”单独的Word文档。我试图移动到“母版”的末尾,复制整个“临时”并粘贴到“母版”,然后在“母版”上输入一个分页符。我在“.Selection.EndKey单位:=wdStory Extend:=wdMove”、“.Add.Content.Paste”和“.Selection.InsertBreak类型:=7”上遇到错误,我不确定原因。我将迭代多个“临时”文档,并将它们逐个添加到“主控”中,但在我能够完成从“临时”到“
如果尚未在Excel VBA项目中添加对Word的引用,则诸如wdStory等常量将无法用于Excel VBA。如果您在模块中使用OptionExplicit(您绝对应该这样做),这将被标记
您需要添加引用,或者在VBA中声明缺少的常量及其值。如果您尚未在Excel VBA项目中添加对Word的引用,则Excel VBA将无法使用
wdStory
等常量。如果您在模块中使用选项Explicit
,则会标记此选项(您绝对应该这样做)。您需要添加引用,或者在VBA.Hi.Tim中声明缺少的常量及其值。我使用的是对单词Object“With MasterWordObj”的引用,该块只将包含的代码范围限定为对象变量。您需要添加对Word对象库的引用。参见-我添加了“Word”参考库。我已经选择了Excel参考库。现在开始工作了!谢谢你,蒂姆。你想在里面填个答案,这样我就可以给你投票了吗?你还没有输入任何变量。因此,它们都是默认类型,即Variant
。您应该始终像这样声明变量:Dim Name为Type
Public wb As Excel.Workbook
Public Path As String
Public MasterWordObj
Public MasterCOI
Public TempWordObj
Public TempCOI
Sub COI()
'Initialize Worksheet/Workbook and unprotect worksheet and cells
ActiveSheet.Unprotect
ThisWorkbook.Sheets("COI").Cells.Locked = False
Set wb = ActiveWorkbook
On Error GoTo ErrorHandler
'Path for Master COI Template
Path = "xxx"
'Create a Master Word Session
Set MasterWordObj = CreateObject("Word.Application")
Set MasterCOI = MasterWordObj.Documents.Add
'Define Path for Temporary COI Template
Path = "XXX"
'Create a Temp Word Session
Set TempWordObj = CreateObject("Word.Application")
Set TempCOI = TempWordObj.Documents.Add(Path)
'Activate Temporary Word Template, Update Fields, Copy All
With TempWordObj
.Visible = True
.Selection.WholeStory
.Selection.Fields.Update
.Selection.WholeStory
.ActiveWindow.WindowState = 1
.Activate
.Selection.WholeStory
.Selection.Copy
End With
'Paste and insert Page Break in Master Template
With MasterWordObj
.Visible = True
.ActiveWindow.WindowState = 1
.Selection.EndKey unit:=wdStory, Extend:=wdMove
.Add.Content.Paste
.Selection.InsertBreak Type:=7
.Activate
End With
'Release the Word objects to save memory and exit macro
ErrorExit:
Set MasterWordObj = Nothing
Set TempWordObj = Nothing
Exit Sub
'Error Handling routine
ErrorHandler:
If Err Then
MsgBox "Error No: " & Err.Number & "; There is a problem"
If Not MasterWordObj Is Nothing Then
MasterWordObj.Quit False
End If
If Not TempWordObj Is Nothing Then
TempWordObj.Quit False
End If
Resume ErrorExit
End If
End Sub