首页 > 解决方案 > VBScript 不会将复制的 Excel 插入特定页面上的 Word

问题描述

我尝试将 Excel 中的一部分复制到特定(第五)页上的 word 中。它将excel部分复制到word中,但总是在第一页。

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\test.xlsx")
Set objwdapp = CreateObject("Word.Application")
Set objSelection = objwdapp.Selection

objExcel.Worksheets("Sheet1").Range("A1:D4").Copy
'Declare Object variables for the Word application and file or document
Dim wddoc
'Declare a String variable for the file name and folder path
Dim strdocname
'error handling is extremely important in making Excel work with Word
On Error Resume Next
'GetObject needs two parameters. The first is optional
Set objwdapp = GetObject(, "Word.Application")
If Err.Number = 429 Then
Err.Clear
'we create a new instance of MS Word
Set objwdapp = CreateObject("Word.Application")
End If
'Our application is made visible
objwdapp.Visible = True
strdocname = "C:\test.docx"
'we activate our MS Word instance
objwdapp.Activate
Set wddoc = objwdapp.Documents(strdocname)
'we open MS Word file if it is not open
If wddoc Is Nothing Then Set wddoc = objwdapp.Documents.Open(strdocname)
wddoc.Activate
'''''' this doesn't work''''''
objSelection.GoTo wdGoToPage, wdGoToAbsolute, 5
objSelection.TypeText "Test"
wddoc.Range.Paste
''''''''''''''''''''''''''''''
wddoc.SaveAs("C:\test1.docx")
objwdapp.Quit
'Here we free memory allocated to our two object variables
Set wddoc = Nothing
Set objwdapp = Nothing
'The following line of code removes the selection of range A1:D4 in Excel
Application.CutCopyMode = False
objWorkbook.Close
objExcel.Quit 

我还尝试在特定单词之后插入 Excel 部分,例如:

objSelection.InsertAfter "testing"

它还将该部分粘贴在第一页中。有人有想法吗?

标签: excelms-wordvbscript

解决方案


您的代码过于冗长。除其他外,它会尝试两次创建 Word 实例。所有你需要的是:

Set ObjXl = CreateObject("Excel.Application")
Set ObjWkBk = ObjXl.Workbooks.Open("C:\test.xlsx")

Set ObjWd = CreateObject("Word.Application")
Set ObjDoc = ObjWd.Documents.Open("C:\test.docx")

ObjWkBk.Worksheets("Sheet1").Range("A1:D4").Copy
ObjDoc.Range.GoTo(1, 1, 5).GoTo(-1, , , "\page").Paste
ObjDoc.SaveAs ("C:\test1.docx")

ObjDoc.Close: ObjWd.Quit: ObjWkBk.Close: ObjXl.Quit
Set ObjDoc = Nothing: Set ObjWd = Nothing: Set ObjWkBk = Nothing: Set ObjXl = Nothing

推荐阅读