excel - 从 Excel 打开 Word 文档并将其保存到新文件位置
问题描述
我正在尝试从 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
解决方案
谢谢 BigBen,只要选择了 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
推荐阅读
- sql-server - SQLCMD 在第一个结果返回 0 行后不打印结果消息
- python - 有没有更有效的方法来创建文件夹?
- gremlin - Rexster 上的 gremlin 控制台(http://localhost:8182/doghouse/main/gremlin/graph)不工作
- binary-tree - 平衡 BST 与平衡二叉树:复杂性
- html - 如何使背景从顶部和底部略微淡化?
- javascript - Object.assign 输出不正确
- sql-server - 使用 string.Format 时,Entity Framework Core 中的原始 SQL 查询无法正常工作
- javascript - 刀片中的 Laravel 本地化下拉菜单
- java - udp 标头行中的空指针异常:“Udp udp = packet.getHeader(new Udp());” 为什么 JNETPCAP 无法初始化 Udp 对象
- android - 如何让 Jenkins 在 Android Studio 中运行与“检查代码”相同的操作