2013-06-20 114 views
0

我試圖用excel宏打開word文件& copy &將一些數據從excel粘貼到打開的word文件中。然後以另存爲 word文件中的相同的目錄的excel文件。但面臨錯誤。請幫忙。 這是我的代碼。使用excel生成word文件在excel同一目錄中vba

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 
+2

'面臨errors'?什麼樣的錯誤?哪裏?你需要在你的問題上更具體。 –

回答

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 
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