Excel VBA сохранить файл как документ Word в папке по умолчанию - PullRequest
0 голосов
/ 04 ноября 2018
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 голосов
/ 04 ноября 2018
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

Привет всем, Спасибо вам за помощь. Мне удалось решить мою проблему с помощью приведенного выше кода, но, к сожалению, не смог сделать это с помощью диалогового окна просмотра местоположения. Я надеюсь, что это станет полезным для всех, кто в этом нуждается.

Однако, если кто-нибудь знает, как реализовать расположение папки просмотра с помощью этого кода, будет лучше и полезнее для других.

...