简体   繁体   English

邮件合并来自 Excel 数据的字

[英]MailMerge Word from Excel data

I tried to MailMerge Word File using VBA codes(in Excel).我尝试使用 VBA 代码(在 Excel 中)MailMerge Word 文件。 When I run the Macro(Code that I wrote), Opening the word file works fine.当我运行宏(我编写的代码)时,打开 word 文件工作正常。 However in selecting table in Word for mailmerge, there's no table in selecting option.但是在 Word 中为 mailmerge 选择表格时,选择选项中没有表格。 Obviously, I typed refData(Excel file) as显然,我输入了 refData(Excel file) 作为

refData = "W:\30 Offer\03 MECHANICAL\*Project_Offer_Number_for MECH_210302_ver2.xlsm*"

But in Word file, it is recognized as "W:\30 Offer\03 MECHANICAL.xls" --> and there's no table.但是在 Word 文件中,它被识别为“W:\30 Offer\03 MECHANICAL.xls” --> 并且没有表格。

so, I can't click the 'OK button '.所以,我无法单击“确定按钮”。 so, I clicked cancel, the the debug pop-up appears with run time error 4198.所以,我点击取消,调试弹出窗口出现运行时错误 4198。

Mail Merge part is located at the bottom of codes.邮件合并部分位于代码的底部。 I tried hard to fine the reason, but I'm new in VBA, so it's quiet hard to find and fix it.我努力解释原因,但我是 VBA 的新手,所以很难找到并修复它。 So, I need some helps.所以,我需要一些帮助。 If you have time to read my codes, please help me.如果您有时间阅读我的代码,请帮助我。 Thank you.谢谢你。

Private Function folder_exister(flderName As String) As Boolean 'Existing Folder Tester

    If Len(Dir(flderName, vbDirectory)) <> 0 Then
        folder_exister = True
    Else
        folder_exister = False
    End If

End Function
Sub Gen_Offer_folder()

'Common Declaration-------------------------------------------------------------------
Dim r As Integer 'Codes for Latest Row
    Sheets("Offer").Select
    Cells(14, 2).Select
    Selection.End(xlDown).Select
    r = Selection.Row
  
Dim CoName As String, EndCusName As String
Dim OffrNm As String, Pjt As String
Dim ResPer As String

    CoName = Cells(r, 4).Value
    EndCusName = Cells(r, 5).Value
    OffrNm = Cells(r, 2).Value
    ResPer = Cells(r, 6).Value
    Pjt = Cells(r, 3).Value

Dim MainDir As String
Dim ComDir As String
Dim PjtDir As String
Dim TempDir As String

    MainDir = "W:\30 Offer\03 MECHANICAL"
    ComDir = "W:\30 Offer\03 MECHANICAL\" & CoName
    PjtDir = "W:\30 Offer\03 MECHANICAL\" & CoName & "\" & OffrNm & " " & EndCusName & " " & Pjt
    TempDir = MainDir & "\_New Rule_Customer location\Offer No_project name"



'Create Folders & Files---------------------------------------------------------
Dim FSO As Object
Dim strFromFolder As String
Dim strToFolder As String

    If folder_exister(ComDir) Then 'create sub-folders in existing folder
        If folder_exister(PjtDir) Then
            Set FSO = CreateObject("scripting.filesystemobject")
                strFromFolder = "W:\30 Offer\03 MECHANICAL\_New Rule_Customer location\Offer No_project name"
                strToFolder = PjtDir
                FSO.CopyFolder _
                Source:=strFromFolder, Destination:=strToFolder, overwritefiles:=True
        Else
            MkDir PjtDir
            
             Set FSO = CreateObject("scripting.filesystemobject")
                strFromFolder = "W:\30 Offer\03 MECHANICAL\_New Rule_Customer location\Offer No_project name"
                strToFolder = PjtDir
                FSO.CopyFolder _
                Source:=strFromFolder, Destination:=strToFolder, overwritefiles:=True
        End If
        
    Else 'create sub-folders in generated folder
        MkDir ComDir
        MkDir PjtDir
                        
        Set FSO = CreateObject("scripting.filesystemobject")
            strFromFolder = "W:\30 Offer\03 MECHANICAL\_New Rule_Customer location\Offer No_project name"
            strToFolder = PjtDir
            FSO.CopyFolder _
            Source:=strFromFolder, Destination:=strToFolder, overwritefiles:=True
    End If

Set FSO = Nothing


'Fill the calc sheet-------------------------------------------------------------
Dim a As String, b As String, c As String, d As String, e As String, f As String, g As String, h As String

    a = ThisWorkbook.Sheets("Offer").Cells(r, 2).Value  'Offer Number
    b = ThisWorkbook.Sheets("Offer").Cells(r, 3).Value  'Pjt Name
    c = ThisWorkbook.Sheets("Offer").Cells(r, 4).Value  'Customer Name
    d = ThisWorkbook.Sheets("Offer").Cells(r, 5).Value  'End Customer Name
    e = ThisWorkbook.Sheets("Offer").Cells(r, 6).Value  'Resp. Person

Dim wkb As Workbook
Application.ScreenUpdating = False
    Set wkb = Workbooks.Open(PjtDir & "\01_COSTS\13_COST_BASIS\" & "Offer calc_offerNr_pjt name_date.xlsx")
    
    With wkb
    
        With .Worksheets("Calc sheet")
        
            .Range("A3").Value = Date    'Date
            .Range("J14").Value = Date   'Date
            .Range("G12").Value = Date   'Date
            .Range("B3").Value = e       'Resp. Name
            .Range("J13").Value = e      'Resp. Name
            .Range("G13").Value = Today  'Updated Day <-- Today
      
            .Range("B10").Value = c
            .Range("B11").Value = d
            .Range("B12").Value = b
        
            .Range("G10").Value = a
        
        End With
        
    .Close SaveChanges:=True      'save changes then close
    
    End With

Set wkb = Nothing


'change offer calc name------------------------------------------------------------
Dim oldName As String, newName As String

    oldName = PjtDir & "\01_COSTS\13_COST_BASIS\Offer calc_offerNr_pjt name_date.xlsx"
    newName = PjtDir & "\01_COSTS\13_COST_BASIS\Offer calc_" & OffrNm & "_" & EndCusName & "_" & Pjt & "_" & Date & ".xlsx"
    
    
    On Error GoTo Here 'If the File is aready exist, then These Codes DO NOT Create New One or Overwite.
    Name oldName As newName

Exit Sub
Here:
    MsgBox "Already Existing Calc Sheet File"
   
   
   
   
'Mail Merge(Word File)///////////////////////////////////////////////////////////////

'Create Offer doc sheet at Calc Sheet for MailMerge
With ThisWorkbook
         .Sheets("for_MailMerge").Range("a2").Value = Pjt
         .Sheets("for_MailMerge").Range("b2").Value = OffrNm
         .Sheets("for_MailMerge").Range("c2").Value = CoName
         .Sheets("for_MailMerge").Range("d2").Value = EndCusName
         .Sheets("for_MailMerge").Range("e2").Value = Date
         .Sheets("for_MailMerge").Range("f2").Value = ResPer
End With



'Create Word File Object
Dim Wrd As Object
Set Wrd = CreateObject("word.application")
Wrd.Visible = True


Dim wrdPath As String, refData As String, xlConnectionString As String
wrdPath = "W:\30 Offer\03 MECHANICAL\_New Rule_Customer location\Offer No_project name\02_OFFER\Offer_OfferNr_pjt name_date.doc"
refData = "W:\30 Offer\03 MECHANICAL\Project_Offer_Number_for MECH_210302_ver2.xlsm"



'Open THE Word File
Wrd.Documents.Open Filename:=wrdPath

'Write on Word
Wrd.ActiveDocument.MailMerge.MainDocumentType = wdFormLetters

'Define Connection String
xlConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" _
                            & "User ID=Admin;" _
                            & "Data Source=" + refData + ";" _
                            & "Mode=Read;" _
                            & "Extended Porperties=""" _
                            & "HDR=YES;" _
                            & "IMEX=;"";" _
                            & "Jet OLEDB:System database="""";" _
                            & "Jet OLEDB:Regist"

'Open a Connection to the Excel 'For word template file
With Wrd.ActiveDocument.MailMerge
        .OpenDataSource _
            Name:=refData, _
            LinkToSource:=True, _
            Connection:=xlConnectionString, _
            SQLStatement:="SELECT * FROM 'for_MailMerge$`"

        'Simulate running the mail merge and return any errors
        .Check
        
        'We can see either the Values(False) or the Fields Name(True)
        .ViewMailMergeFieldCodes = False
        
        'Specify the destination
        .Destination = wdSendToNewDocumunent
        
        'Execute the mail merger, and don't pause for errors
        .Execute Pause:=False
End With

    'for Created word file
    Wrd.ActiveDocument.SaveAs Filename:=PjtDir & "\02_OFFER" & "Offer_" & OffrNm & "_" & Pjt & "_" & Date & ".doc"
    Wrd.ActiveWindow.Close
         
    Wrd.ActiveDocument.Close SaveChanges:=True
    Wrd.Quit
    
    Set Wrd = Nothing
    
    MsgBox "Completed"
    ActiveWorkbook.Save

   
End Sub

If your Word document has been saved as a mailmerge main document, your code will stall waiting for you to answer the mailmerge SQL prompt.如果您的 Word 文档已保存为 mailmerge 主文档,您的代码将停止等待您回答 mailmerge SQL 提示。 To overcome that you need to employ:为了克服这个问题,您需要采用:

Wrd.DisplayAlerts = wdAlertsNone

before:前:

Wrd.Documents.Open Filename:=wrdPath

Your SQL statement is also malformed.您的 SQL 语句也格式不正确。

For more, see Run a Mailmerge from Excel, Sending the Output to Individual Files in: https://www.msofficeforums.com/mail-merge/21803-mailmerge-tips-tricks.html For more, see Run a Mailmerge from Excel, Sending the Output to Individual Files in: https://www.msofficeforums.com/mail-merge/21803-mailmerge-tips-tricks.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM