我试图使用excel macro& amp打开一个word文件。副本&将一些数据从excel粘贴到打开的word文件中。然后在excel文件的相同目录中另存为 word文件。但面临错误。请帮忙。 这是我的代码。
enter code here
Sub OICD()
Const strPath As String = "C:\Users\owner\Desktop\OICD TEMPLATES\OICD_"
Dim strFileName As String
strFileName = InputBox("Please enter file name", "Create new file")
If strFileName = vbNullString Then Exit Sub
Dim Word As Object: Set Word = CreateObject("word.application")
Dim docWD As Word.Document
Word.Visible = True
Set docWD = Word.Documents.Open("C:\Users\owner\Desktop\OICD TEMPLATES\OICD Template V1.docx")
docWD.SaveAs ThisWorkbook.Path & "\" & strFileName), FileFormat:=wdFormatDocument
ThisWorkbook.Sheets("REPORT").Range("C7:J56").Copy
Word.Selection.Paste
End Sub
答案 0 :(得分:1)
您的代码因各种原因而失败。您应该学会调试以轻松找到问题(从代码执行,按f8直到它因特定原因在特定行崩溃)。
此版本可以满足您的需求:
Sub OICD()
Const strPath As String = "C:\Users\owner\Desktop\OICD TEMPLATES\OICD_\" 'The last characters has to be a "\"
Dim strFileName As String
Dim extension As String
strFileName = InputBox("Please enter file name", "Create new file")
If strFileName = vbNullString Then Exit Sub
extension = ".docx" '".doc"
Dim Word As Object: Set Word = CreateObject("Word.Application")
Word.Visible = True
Set docWD = Word.Documents.Open(strPath & strFileName & extension)
docWD.SaveAs ThisWorkbook.Path & "\" & strFileName, FileFormat:=wdFormatDocument
ThisWorkbook.Sheets("REPORT").Range("C7:J56").Copy
Word.Selection.Paste
End Sub
答案 1 :(得分:0)
Option Explicit
Sub Wordcreation()
Dim WdObj As Object, fname As String
fname = "Word"
Set WdObj = CreateObject("Word.Application")
WdObj.Visible = False
Range("A1:E8").Select
Selection.Copy 'Your Copy Range
WdObj.Documents.Add
WdObj.Selection.PasteSpecial
Application.CutCopyMode = False
If fname <> "" Then 'make sure fname is not blank
With WdObj
.ChangeFileOpenDirectory "D:\chandra" 'save Dir
.ActiveDocument.SaveAs Filename:=fname & "Chandra.doc"
End With
Else:
MsgBox ("File not saved, naming range was botched, guess again.")
End If
With WdObj
.ActiveDocument.Close
.Quit
End With
Set WdObj = Nothing
End Sub