如果数据源没有记录,请跳过MS Word邮件合并

时间:2019-02-09 07:52:23

标签: vba vbscript ms-word docx-mailmerge

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

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

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,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

感谢所有帮助,在此先感谢您。

1 个答案:

答案 0 :(得分:0)

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

您可以检查它DataSource是什么(或者根据需要检查否):

If .DataSource Is Nothing Then ...

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

If .DataSource.RecordCount = 0 Then