使用Excel VBA打开并保存Word文档并不起作用

时间:2015-11-02 14:44:07

标签: excel vba excel-vba

我想打开Word文档,粘贴Excel文件中的数据,然后保存该Word文档。

打开Word并粘贴数据工作正常,但由于行" ChDir" C:\ My Documents \&#34的问题,它无法保存文件;

我在这里缺少什么?

Sub macro()

Dim WordApp As Word.Application
Dim WordDoc As Word.Document

Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
WordApp.Activate

Set WordDoc = WordApp.Documents.Add

Range("A1:C33").Copy

WordApp.Selection.PasteSpecial Link:=False, DataType:=wdPasteRTF, _Placement:=wdInLine, DisplayAsIcon:=False

WordDoc.PageSetup.LeftMargin = CentimetersToPoints(1.5)
WordDoc.PageSetup.TopMargin = CentimetersToPoints(1.4)
WordDoc.PageSetup.BottomMargin = CentimetersToPoints(1.5)

ChDir "C:\My Documents\Test"
ActiveDocument.SaveAs "Archief" & Format(Now, "yyyymmdd") & ".docx"

Set WordDoc = Nothing
Set WordApp = Nothing

End Sub

2 个答案:

答案 0 :(得分:0)

创建变量以包含文件的路径和名称会更容易,如下所示:

Dim FileFullName As String

FileFullName = Environ("userprofile") & "\My Documents\Test" & "\" & "Archief" & Format(Now, "yyyymmdd") & ".docx"
ActiveDocument.SaveAs FileFullName

答案 1 :(得分:0)

试试这个:

Dim FileName2        As String

Set appWrd = CreateObject("Word.Application")

   appWrd.DisplayAlerts = False
    FileName2 = Document.Path & "\" & ".docx"
    appWrd.ActiveDocument.SaveAs FileName:=FileName2