【问题标题】:Opening and Saving Word Document to new File Location from Excel从 Excel 打开 Word 文档并将其保存到新文件位置
【发布时间】:2019-04-30 13:56:30
【问题描述】:

我正在尝试从 excel 打开 word 文档,然后使用对话框另存为新的文件位置。

问题是它保存的是excel文件而不是打开的word文件。

Option Explicit
Sub SaveWordDoc()
    Dim WordApp As Object, WordDoc As Object, path As String
    Dim dlgSaveAs As FileDialog

    ' Allows word document to be selected and opened
    With Application.FileDialog(msoFileDialogOpen)
    .Show
    If .SelectedItems.Count = 1 Then
        path = .SelectedItems(1)
    End If
    End With

    If path = "" Then
        Exit Sub
    End If


    Set WordApp = CreateObject("Word.Application")
    Set WordDoc = WordApp.Documents.Open(path)
    WordApp.Visible = False

    'Opens Save As dialog box
    Set dlgSaveAs = Application.FileDialog( _
    FileDialogType:=msoFileDialogSaveAs)
    dlgSaveAs.Show

    WordApp.ActiveDocument.Close
    WordApp.Quit
    Set WordApp = Nothing
    Set WordDoc = Nothing
End Sub

【问题讨论】:

  • Application.FileDialog 中的 Application 指的是 Excel 实例。如果您想继续在 Excel 中使用对话框(而不是利用 WordApp 实例),也许可以尝试 Application.GetSaveAsFilename 方法,该方法在不保存任何文件的情况下获取文件名。然后使用它返回的文件名使用SaveAs2方法保存WordDoc
  • 尝试 'Set dlgSaveAs = WordApp.Application.FileDialog( _ FileDialogType:=msoFileDialogSaveAs) dlgSaveAs.Show' 以使用文件对话框。要将 word 文档保存到您从使用 WordDoc.SaveAs2 获得的同一文件夹中。

标签: excel vba ms-word


【解决方案1】:

感谢 BigBen,只要选择了 a word 文档格式,您的建议就很有效。

Option Explicit
Sub Test()
    Dim WordApp As Object, WordDoc As Object, path As String
    Dim dlgSaveAs As FileDialog, fileSaveName As Variant

    ' To get the code to function I had to include the Microsoft Word 16 Object
    'Library.

    'From the excel VBA editor window. Tools > References then ensure Microsoft Word
    '16.0 Object Library is checked.

    ' Allows word document to be selected and opened
    With Application.FileDialog(msoFileDialogOpen)
    .Show
    If .SelectedItems.Count = 1 Then
        path = .SelectedItems(1)
    End If
    End With

    If path = "" Then
        Exit Sub
    End If


    Set WordApp = CreateObject("Word.Application")
    Set WordDoc = WordApp.Documents.Open(path)
    WordApp.Visible = False

    ' Allows word document to be saved under a different file location and name
    fileSaveName = Application.GetSaveAsFilename( _
    fileFilter:="Word Documents (*.docx), *.docx")
    WordApp.ActiveDocument.SaveAs2 Filename:=fileSaveName, _
        FileFormat:=wdFormatDocumentDefault

    WordApp.ActiveDocument.Close
    WordApp.Quit

    Set WordApp = Nothing
    Set WordDoc = Nothing
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-21
    • 2016-06-26
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 2013-10-08
    • 2017-07-31
    • 2014-04-04
    相关资源
    最近更新 更多