Excel macro - open specific word file

余生长醉 提交于 2020-06-17 02:33:57

问题


I haven't found anything that can help me.

I'm trying to open a certain word file, have some data written in it and saved under a different name. This is what I have so far:

Dim appWD As Word.Application
Set appWD = CreateObject("Word.Application.8")
Set appWD = New Word.Application
Dim docWD As Word.Document
Set docWD = appWD.Documents.Open("C:\Documents and Settings\Excel macro\Standaard.docx")
appWD.Visible = True
'
' Data is selected and copied into "Design"
'
 Copy all data from Design
Sheets("Design").Select
Range("A1:G50").Copy
' Tell Word to create a new document
appWD.Documents.Add
' Tell Word to paste the contents of the clipboard into the new document
appWD.Selection.Paste
' Save the new document with a sequential file name
Sheets("Sheet1").Select
appWD.ActiveDocument.SaveAs Filename:=ThisWorkbook.Path & "/" & "TEST" & Range("C8").Text
' Close this new word document
appWD.ActiveDocument.Close
' Close the Word application
appWD.Quit

At the moment all it does is; open the Standaard.docx file, open a new file and paste everything in the new file and saves. It should open the Standaard.docx file, paste it in there and save under a new name.

Many thanks!


回答1:


The reason that it opens a new document is because you have the line:

appWD.Documents.Add

in your code before the line:

appWD.Selection.Paste

if you remove the appWD.Documents.Add Word will paste into your active document (i.e. "Standaard.docx").

Just one other point, you do not need the line:

Set appWD = CreateObject("Word.Application.8")

as you immediately initialise a new Word application in the line below it with:

Set appWD = New Word.Application



回答2:


This macro opens a file then saves it as a new file name in a different folder based on info updated in the sheet1 of the Excel file

Sub OpenDocFileNewName()


'
' OpenDocFileNewName Macro

'
'
    Set WordApp = CreateObject("Word.Application.8")

Set WordDoc = WordApp.Documents.Open("C:\Users\mmezzolesta\Documents\_TestDataMerge\STANDARD.docx")

WordApp.Visible = True

'
'
'Save as new file name

Sheets("Sheet1").Select

WordApp.ActiveDocument.SaveAs Filename:=("C:\Users\mmezzolesta\Documents\_TestMailMergeAuto") & "/" & Range("A2") & "Standard-Grounding-" & Range("e2").Text

WordApp.ActiveDocument.Close

WordApp.Quit

'
'
End Sub


来源:https://stackoverflow.com/questions/5310376/excel-macro-open-specific-word-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!