[英]Generating word file in the same directory of excel using excel vba
I was trying to open a word file using excel macro & copy & paste some data from excel to the opened word file. 我试图使用excel宏打开Word文件,并将Excel中的某些数据复制并粘贴到打开的Word文件中。 Then to save as the word file in the same directory of excel file.
然后将其另存为 Word文件到excel文件的同一目录中。 But facing errors.
但是面临错误。 Please help.
请帮忙。 Here is my code.
这是我的代码。
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
Your code fails because of various reasons. 您的代码由于各种原因而失败。 You should learn to debug to easily locate the problems (execute from the code, press f8 until it crashes on certain line for certain reason).
您应该学习调试以轻松定位问题(从代码执行,按f8直到由于某些原因在特定行崩溃)。
This version does what you want: 此版本可满足您的需求:
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.