首页 > 解决方案 > VBA 将 Word Doc 打印为 PDF,并使用 Mailmerge 字段中的密码

问题描述

我正在对大型 Excel 数据集执行邮件合并练习。我需要将 word 文档中的 PDF 与单独的密码合并 - 密码是我的 excel 文件中的一个字段。

我下面的代码要求提供批号和位置。我有某些行与 excel 文件中的批号匹配。我有以下运行并成功打印了我输入的批次,但我不知道如何将个人密码放在 PDF 上。任何帮助将不胜感激。我有 PDF-XChange 作为我通常用来在单个 PDF 上设置密码的程序。

Sub Merge_To_Individual_PDF()

'
' Merge_To_Individual_PDF Macro
'
'
Application.ScreenUpdating = True
Dim StrFolder As String, StrName As String, MainDoc As Document, TargetDoc As Document, i As Long, j As Long, K As String, Newfolder As String, MyFolder As String, L As Long
Const StrNoChr As String = """*./\:?|"
Set MainDoc = ActiveDocument
K = "Errors"
'Batch to Print
myValue = InputBox("Batch Number")
If StrPtr(myValue) = 0 Then Exit Sub
If myValue = "" Then Exit Sub
If TypeName(myValue) = "Boolean" Then Exit Sub
MyFolder = InputBox("Copy Paste Local File Location Here")
With MainDoc
'Folder name
  If MyFolder = "" Then
  StrFolder = "C:\Users\Mathun\test\"
  Else: StrFolder = MyFolder & "\"
  End If
  L = 0
  Application.StatusBar = L
  With .MailMerge
    .Destination = wdSendToNewDocument
    .SuppressBlankLines = True
    On Error Resume Next
   For i = 1 To .DataSource.RecordCount
      With .DataSource
        .FirstRecord = i
        .LastRecord = i
        .ActiveRecord = i
        If Trim(.DataFields("Pack_Ref")) = "" Then Exit For
        StrName = .DataFields("Pack_Ref")
         'Only print this batch
        If .DataFields("BatchNumber") <> myValue Then GoTo NextRecord
       
        
      End With
      .Execute Pause:=False
      If Err.Number = 5631 Then
        Err.Clear
        K = K & StrName
        GoTo NextRecord
      End If
      Newfolder = StrFolder & myValue
      MkDir Newfolder
      
        StrName = Trim(StrName)
               With ActiveDocument
        Selection.WholeStory
        ActiveDocument.Fields.ToggleShowCodes
        Selection.Fields.Update
        ', Password:=StrName
        ActiveDocument.SaveAs2 FileName:=StrFolder & myValue & "\" & StrName & ".docx", FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
        .Close
        L = L + 1
        'and/or:
        ActiveDocument.SaveAs2 FileName:=StrFolder & myValue & "\" & StrName & ".pdf", FileFormat:=wdFormatPDF, AddToRecentFiles:=False
        .Close SaveChanges:=False
        
        End With
NextRecord:
    Next i
  End With
End With
Application.ScreenUpdating = True
End Sub

标签: vbapdfpasswordswordmailmerge

解决方案


推荐阅读