0

我试图使用 excel 宏打开一个 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
4

2 回答 2

1
          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
于 2013-11-21T04:40:07.987 回答
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
于 2013-06-20T07:53:47.667 回答