首页 > 解决方案 > Excel 到 PDF - 如何指定宏将保存 PDF 文件的位置

问题描述

我正在运行这段代码,它基本上将我的 excel 表的最后一行保存到 PDF 文件中,它将 PDF 文件保存到 excel 表和我的 word 模板所在的文件夹中(它们在同一个文件夹中)。

如何设置不同的位置作为保存点?
我想将用户限制在特定位置,该位置不是 excel 表和 word 模板所在的文件夹。

例如:我希望将文件保存在这里:“C:\Users\User\Desktop\Folder”
另外,请指导我如何将它实现到我的代码中,这有点新。

Sub RunMerge()
' Sourced from: https://www.msofficeforums.com/mail-merge/21803-mailmerge-tips-tricks.html
' Note: this code requires a reference to the Word object model to be set, via Tools|References in the VBE.
Application.ScreenUpdating = False
Dim StrMMSrc As String, StrMMDoc As String, StrMMPath As String, StrName As String
Dim i As Long, j As Long
Const StrNoChr As String = """*./\:?|"
Dim wdApp As New Word.Application, wdDoc As Word.Document
wdApp.Visible = False
wdApp.DisplayAlerts = wdAlertsNone
StrMMSrc = ThisWorkbook.FullName
StrMMPath = ThisWorkbook.Path & "\"
StrMMDoc = StrMMPath & "MailMergeDocument.doc"
Set wdDoc = wdApp.Documents.Open(Filename:=StrMMDoc, AddToRecentFiles:=False, ReadOnly:=True, Visible:=False)
With wdDoc
  With .MailMerge
    .MainDocumentType = wdFormLetters
    .OpenDataSource Name:=StrMMSrc, ReadOnly:=True, AddToRecentFiles:=False, _
      LinkToSource:=False, Connection:="Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;" & _
      "Data Source=StrMMSrc;Mode=Read;Extended Properties=""HDR=YES;IMEX=1"";", _
      SQLStatement:="SELECT * FROM `Sheet1$`"
    i = .DataSource.RecordCount
      .Destination = wdSendToNewDocument
      .SuppressBlankLines = True
      With .DataSource
        .FirstRecord = i
        .LastRecord = i
        .ActiveRecord = i
        StrName = .DataFields("Name")
      End With
      .Execute Pause:=False
      For j = 1 To Len(StrNoChr)
        StrName = Replace(StrName, Mid(StrNoChr, j, 1), "_")
      Next
      StrName = Trim(StrName)
      With wdApp.ActiveDocument
        'Add the name to the footer
        '.Sections(1).Footers(wdHeaderFooterPrimary).Range.InsertBefore StrName
        '.SaveAs Filename:=StrMMPath & StrName & ".docx", FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
        ' and/or:
        .SaveAs Filename:=StrMMPath & StrName & ".pdf", FileFormat:=wdFormatPDF, AddToRecentFiles:=False
        .Close SaveChanges:=False
      End With
    .MainDocumentType = wdNotAMergeDocument
  End With
  .Close SaveChanges:=False
End With
wdApp.DisplayAlerts = wdAlertsAll
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing
Application.ScreenUpdating = False
End Sub

标签: excelvbapdfms-wordsave

解决方案


所以改变:

StrMMPath = ThisWorkbook.Path & "\"

指向您要保存文件的位置。例如:

StrMMPath = C:\Users\" & Environ("Username") & "\Desktop\Folder\"

很高兴看到你真的在这一切上投入了一些精力。您获得代码的网站甚至告诉您如何进行这样的更改!!!到目前为止,您在多个线程中所做的一切似乎都被要求接受解决方案和/或对您从另一个站点复制的代码的修改。

PS:投票给对你有帮助的答案也是一种常见的礼貌。


推荐阅读