显示一个列表以选择word文档,然后宏将合并从excel到word的信息

时间:2015-06-02 17:29:14

标签: excel-vba vba excel

这是我用word合并的宏。 我意识到我需要做更多的事情,我会从一系列可用的单词文档中选择要合并的表单(xx1,xx2 ... xx7)。有6个word文档,其中2个我需要打开另一个常用word文档(xx7)。即。当我选择word文档xx3或xx6时,我需要打开2个word文档。如果我选择xx3 word文档然后打开xx3和xx7,如果我选择xx6 word文档,则打开xx6和xx7。在此期间,xx1,xx2,xx4,xx5将打开一个word文档。 我不想用另一个word文档名重复这个宏7次。我有机会在一个宏中覆盖这个吗?谢谢你

Sub RunMergeAttachBOccupantProtection()

   Const wdFormLetters = 0
   wdOpenFormatAuto = 0
   Const wdSendToNewDocument = 0
   wdDefaultFirstRecord = 1
   wdDefaultLastRecord = -16

    Dim wd As Object
    Dim wdocSource As Object

    Dim strWorkbookName As String

    On Error Resume Next
    Set wd = GetObject(, "Word.Application")
    If wd Is Nothing Then
        Set wd = CreateObject("Word.Application")
    End If
    On Error GoTo 0

    Set wdocSource = wd.Documents.Open("R:\Grants\AttachmentBOccupantProtection.docx")

    strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name

    wdocSource.MailMerge.MainDocumentType = wdFormLetters

    wdocSource.MailMerge.OpenDataSource _
            Name:=strWorkbookName, _
            AddToRecentFiles:=False, _
            Revert:=False, _
            Format:=wdOpenFormatAuto, _
            Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
            sqlstatement:="SELECT * FROM [" & ActiveSheet.Name & "$]"
    With wdocSource.MailMerge
        .Destination = wdSendToNewDocument
        .SuppressBlankLines = True
        With .DataSource
            .FirstRecord = wdDefaultFirstRecord
            .LastRecord = wdDefaultLastRecord
        End With
        .Execute Pause:=False
    End With

    wd.Visible = True
    wdocSource.Close SaveChanges:=False

    Set wdocSource = Nothing
    Set wd = Nothing

End Sub

1 个答案:

答案 0 :(得分:0)

修改您的过程以接受要打开的文档的名称,然后为需要打开的每个文档调用一次。与此类似:

Sub RunMergeAttachBOccupantProtection(DocName as String)
  .
  .
  .
  Set wdocSource = wd.Documents.open("R:\Grants\" & DocName & ".docx")
  .
  .
  .
End Sub

然后你可以用这个进行快速测试:

Sub TestDriver()

  Dim MyDoc as String

  MyDoc = "XX1"

  if MyDoc = "xx3" or MyDoc = "xx6" then
    RunMergeAttachBOccupantProtection("xx3")
    RunMergeAttachBOccupantProtection(MyDoc)
  Else
    RunMergeAttachBOccupantProtection(MyDoc)
  End If

End Sub