0

我目前有 6 个邮件合并模板,我通过以下 vbs 执行。

这将打开根文件夹中的每个文件并运行邮件合并,

VBS

 Set fs = CreateObject("Scripting.FileSystemObject")
    Set rootFolder = fs.GetFolder(fs.GetParentFolderName(wscript.ScriptFullName))
    Set oWord = Createobject("Word.Application")
        oWord.Visible = False

    For Each file in rootFolder.Files
       If LCase(fs.GetExtensionName(file.Name)) = "docx" Then
        Set oDocument = oWord.Documents.Open(file.path)
            oWord.Run "regular_mail"
            oDocument.Close(False)
        Set oDocument = Nothing
       End If
    Next
    oWord.Quit
    set oWord = nothing

vba里面的word,mailmerge是否把它放在指定的文件夹中,当该文件的数据源没有数据时,我得到的是一个错误。因为StrName = .DataFields("pk")不会有任何价值。

我卡住的地方是如何解决该错误,或​​者检查数据源是否为空白,然后继续下一个模板。

每个模板都应保存到一个文件中,以便我的收发室可以打印。

单词中的VBA:

Sub regular_mail()
Dim sDate As String, StrFolder As String, StrName As String, MainDoc As Document, i As Long, j As Long, fso As Object, StrMonthPath As String, StrDayPath As String, StrFileName As String

sDate = Format(Now(), "mmddyy")
Const StrFolderName As String = "C:\Test\Files\"
Set fso = CreateObject("Scripting.FileSystemObject")

    With ActiveDocument.MailMerge
        .Destination = wdSendToNewDocument
        .SuppressBlankLines = True

        With .DataSource
            .FirstRecord = i
        .LastRecord = i
        .ActiveRecord = i

            StrName = .DataFields("pk")
            StrMonthPath = .DataFields("month_path")
            StrDayPath = .DataFields("day_path")
            StrSendDate = .DataFields("send_date")
            StrFileName = sDate & "_" & fso.GetBaseName(ActiveDocument.Name)
        End With
        .Execute Pause:=False



'Creates directory if it doesnt exist

    If Not fso.FolderExists(StrFolderName & StrMonthPath) Then
        fso.CreateFolder (StrFolderName & StrMonthPath)
    End If

    If Not fso.FolderExists(StrFolderName & StrMonthPath & StrDayPath) Then
        fso.CreateFolder (StrFolderName & StrMonthPath & StrDayPath)
    End If


    If Not fso.FolderExists(StrFolderName & StrMonthPath & StrDayPath & "letters\") Then
        fso.CreateFolder (StrFolderName & StrMonthPath & StrDayPath & "letters\")
    End If
    End With



    ActiveDocument.SaveAs2 FileName:=StrFolderName & StrMonthPath & StrDayPath & "letters\" & StrFileName, FileFormat:=16, AddToRecentFiles:=False

    ActiveWindow.Close
End Sub

任何和所有的帮助表示赞赏,在此先感谢您。

4

1 回答 1

0

如果现在无法自己进行测试,您可以使用以下两种方法或其中一种方法:

你可以检查它DataSource什么都没有(或者如果不是什么,你需要):

If .DataSource Is Nothing Then ...

您可以检查数据源中是否有记录:

If .DataSource.RecordCount = 0 Then
于 2019-02-09T08:18:26.843 回答