Excel VBA将文件另存为Word文档在默认文件夹中

时间:2018-11-04 12:22:03

标签: excel vba ms-word save-as

Sub Submit_Click()

Dim wApp As Object
Dim wDoc As Object

Set wApp = CreateObject("Word.Application")
wApp.Visible = True

'Retrieves the word doc template and inserts values from the userform using bookmarks

Set wDoc = wApp.Documents.Open(Filename:="C:\Users\Documents\template1.docx ", ReadOnly:=False)
    With wDoc
    .Bookmarks("bookmark1").Range.Text = Me.TextBox1.Value
    .Bookmarks("bookmark2").Range.Text = Me.TextBox3.Value
    .Bookmarks("bookmark3").Range.Text = Me.TextBox4.Value
    .Bookmarks("bookmark4").Range.Text = Me.TextBox5.Value

'set the default filename

ProposedFileName = Format(Now(), "DD-MMM-YYYY") & "Serial Number" & " " & TextBox1.Value _
& " " & TextBox2.Value & "- RMA" & ".docx"

'trying to save file back to .doc instead of the default .xlms format

Set fd = Application.FileDialog(msoFileDialogSaveAs)
With fd
    .FilterIndex = 2
    .InitialFileName = ProposedFileName
    If .Show Then
        ActiveDocument.SaveAs2 Filename:=.SelectedItems(1), _
            FileFormat:=wdFormatDocumentDefault
    Else
    Call CommandButton4_Click 'cancel save
    End If
End With

Set fd = Nothing

End Sub

大家好,

我上面的脚本只是从我的用户表单中提取的一部分。基本上所有情况都是我的用户窗体打开一个Word文档模板,并使用书签从excel用户窗体中将文本插入文档中。

在用户表单上单击“提交”后,文件对话框打开并带有默认的.xlms,不允许我将其保存回.doc

我一直在搜索和修改脚本,但似乎无法正确执行。如果有人可以告诉我怎么办,我将不胜感激。谢谢。

关于, 凯夫

1 个答案:

答案 0 :(得分:0)

Private Sub SubmitButton_Click()  

'set default file name and file path
ProposedFileName = Format(Now(), "DDMMMYYYY") & " " & TextBox1.Value & "-" & TextBox2.Value & ".doc"
ProposedFilePath = "C:\Users\"

    'save the word document called by excel to a .doc format
    With wApp.FileDialog(msoFileDialogSaveAs)
      wDoc.SaveAs2 ProposedFilePath & ProposedFileName, _
      FilterIndex = 1, _
        FileFormat:=wdFormatDocument
    End With

'unloads the userforms and .doc file after the document is saved
Unload Me
wApp.Quit

'a dialog box pops up after document is saved to say where the file is saved since I was't unable to implement the browse folder option
  MsgBox "The document is saved in " & ProposedFilePath, vbOKOnly
  Cancel = False
Exit Sub

End Sub

大家好, 感谢您的帮助。我已经设法通过上面的代码解决了我的问题,但是不幸的是,使用浏览位置对话框无法解决它。我希望这将对每个需要它的人有用。

但是,如果有人知道如何使用此代码来实现浏览文件夹的位置,对其他人将更好而有用。