-1

I am trying to automate the creation of a word document using the OpenDataSource from MailMerge and using as source a worksheet where previously the data was saved.

The problem is that everytime the wdocSource.MailMerge.OpenDataSource is called the excel pauses with the execution. The process WINWORD.EXE is running but Excel doesn't continue as it were waiting for something to happen and I have to kill the process to make it respond.

I checked these questions but I cannot make it work:

Mailmerge from Excel using Word template VBA

Executing Word Mail Merge

Running a MS Word mail merge from excel

Const sTempSourceSheet = "TempSourceSheet"

Creating worksheet source

Sub PrintArray(Data, SheetName, StartRow)
    Dim Destination As range
    Set Destination = range("A" & StartRow)
    Set Destination = Destination.Resize(1, UBound(Data))
    Destination.FormulaR1C1 = Data
End Sub

''''''''''''''''''''''''''''''''''''''''
' SaveSourceSheet
Public Sub SaveSourceSheet(cols() As String, arr() As String)
On Error GoTo error
    Dim ws As Worksheet

    With ActiveWorkbook
        .Sheets.Add(After:=.Sheets(.Sheets.count)).Name = sTempSourceSheet
    End With

    PrintArray cols, sTempSourceSheet, 1
    PrintArray arr, sTempSourceSheet, 2

done:
    Exit Sub

error:
    With ActiveWorkbook
        .Sheets(sTempSourceSheet).Delete
    End With

    Resume done
End Sub

And the code for runnig the MailMerge

Sub Contract(wordfile As String)
    Dim wd As Object
    Dim wdocSource As Object
    Dim excelfile As String
    Dim strWorkbookName As String
    excelfile = ThisWorkbook.path & "\" & ThisWorkbook.Name
    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(wordfile)

    wdocSource.MailMerge.MainDocumentType = wdFormLetters

    wdocSource.MailMerge.OpenDataSource Name:= _
    excelfile, ConfirmConversions:=False, _
    ReadOnly:=False, LinkToSource:=True, AddToRecentFiles:=False, _
    PasswordDocument:="", PasswordTemplate:="", WritePasswordDocument:="", _
    WritePasswordTemplate:="", Revert:=False, format:=wdOpenFormatAuto, _
    Connection:= _
    "Provider=Microsoft.Jet.OLEDB.4.0;Password="""";" & _
    "User ID=Admin;" & _
    "Data Source=" & excelfile & ";" & _
    "Mode=Read;Extended Properties=" & _
    "HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";" _
    , SQLStatement:="SELECT * FROM `TempSourceSheet$`", SQLStatement1:="", SubType:= _
    wdMergeSubTypeAccess

    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

Any idea?

update

After the changes proposed by @macropod I still have some issues:

In the line .OpenDataSource word shows this message:

enter image description here

Any of the options throws an error:

enter image description here

I checked and the Excel file is present and contains a worksheet with the proper name.

blfuentes
  • 2,731
  • 5
  • 44
  • 72
  • I am confused. Exactly where are these procedures located? Why continue to use Excel and not just Access? Why mail merge and not an Access report? – June7 May 25 '20 at 16:19
  • This is an Excel Macro Application. This code is located in a Form. The user clicks a button in one form and it opens a mask where some data hast to be filled. Then commit and in the background I need to store the data into a worksheet that will serve as source for the word document(created from a template) – blfuentes May 25 '20 at 16:58
  • A Form in Excel? Why the ms-access tag? – June7 May 25 '20 at 17:03
  • The user @braX edited my tags ...ms-access is wrong. I had also a wrong one. Now should be ok – blfuentes May 25 '20 at 17:05
  • Have you tried stepping through your code to see if it hangs on any particular line? Also where and how is `Contract` called? What is the value passed to `wordfile`? – Samuel Everson May 25 '20 at 20:19
  • Yes, I have debugged . `wordfile` is the path of the word document. It hangs exactly here `wdocSource.MailMerge.OpenDataSource` The `Contract` is called within a simple `button_click` – blfuentes May 26 '20 at 06:34
  • You're right, I had to save it as temporary somewhere else and then I could use it as datasource... Still thinking if it would be possible to use the current document as the company has some excell addins that force the user to select some settings while saving an office document and it "breaks the background workflow" I wanted to implement. Unfortunately the macros are loaded dynamically and I should be able to run this functionalities on any empty new excel file. This is a legacy tool I cannot "touch" that much. – blfuentes May 27 '20 at 07:04
  • I am open to use temporary files, at first I started to use a `csv` file and it worked pretty well, but some clients started to become a prompt to choose the delimiter and end of line when loading the `csv` file, so it was not a valid option as they had no idea about it... – blfuentes May 27 '20 at 08:54
  • Actually this is my adapted implementation. I create a new workbook with a new hidden worksheet, paste the data and close the workbook, so the user doesn't see in any case that a "raw data" worksheet is there. Then I load the saved workbook as datasource and finally I delete it – blfuentes May 28 '20 at 07:00

1 Answers1

1

«The problem is that everytime the wdocSource.MailMerge.OpenDataSource is called the excel pauses with the execution. The process WINWORD.EXE is running but Excel doesn't continue as it were waiting for something to happen and I have to kill the process to make it respond.»

That indicates that the document you're trying to open is probably already a mailmerge main document and the code is waiting for you to respond to the SQL query Word produces when opening such documents.

Alternatively, if the document contains auto macros, it could be waiting for a user response.

Your code also contains:

ReadOnly:=False, LinkToSource:=True

which should be:

ReadOnly:=True, LinkToSource:=False

I'd also suggest changing the provider, to:

Microsoft.ACE.OLEDB.12.0

Try the following code:

Sub Contract(wordfile As String)
Dim wdApp As Object, wdDoc As Object
Dim StrMMSrc As String: StrMMSrc = ActiveWorkbook.FullName
If Dir(wordfile) = "" Then
  MsgBox "Cannot find:" & vbCr & wordfile, vbExclamation
  Exit Sub
End If
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If wdApp Is Nothing Then
  Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
With wdApp
  .Visible = True
  .WordBasic.DisableAutoMacros
  .DisplayAlerts = 0 ' wdAlertsNone
  Set wdDoc = .Documents.Open(wordfile)
  With wdDoc
    With .MailMerge
      .MainDocumentType = wdFormLetters
      .Destination = wdSendToNewDocument
      .SuppressBlankLines = True
      .OpenDataSource Name:=StrMMSrc, ReadOnly:=True, AddToRecentFiles:=False, _
        LinkToSource:=False, Connection:="Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;" & _
        "Data Source=StrMMSrc;Mode=Read;Extended Properties=""HDR=YES;IMEX=1"";", _
        SQLStatement:="SELECT * FROM `TempSourceSheet$`", SubType:=wdMergeSubTypeAccess
      With .DataSource
        .FirstRecord = wdDefaultFirstRecord
        .LastRecord = wdDefaultLastRecord
      End With
      .Execute Pause:=False
    End With
    .Close SaveChanges:=False
  End With
End With
Set wdDoc = Nothing: Set wdApp = Nothing
End Sub
macropod
  • 12,757
  • 2
  • 9
  • 21
  • Thanks for the answer, but it is still not working. the `word.exe` is there running but still waiting/stopping on `wdocSource.MailMerge.OpenDataSource` – blfuentes May 26 '20 at 13:46
  • See expanded answer. I've identified some additional issues. – macropod May 26 '20 at 14:31
  • I have updated the question as after aplying your changes it still breaks but seems to go a little bit further. – blfuentes May 26 '20 at 16:23
  • «I have updated the question as after aplying your changes it still breaks but seems to go a little bit further» Now that you've updated your question, it is clear you need to use ActiveWorkbook.FullName instead of ThisWorkbook.FullName. Answer updated (again). – macropod May 26 '20 at 22:51
  • I now get a dialog that asks me to select the datasource and OleDB as option but after confirm it still raises an error telling it cannot open the datasource. I have also tried without the `Connection` option as someone suggested but then it directly states the datasource(workbook) cannot be found. – blfuentes May 27 '20 at 06:20
  • Has the workbook actually been saved? Do you have more than one workbook open? – macropod May 27 '20 at 06:31
  • Now I make it work, as suggested the file had to be saved but I cannot use the same excel document as Word cannot access to it. So I created a temporary excel file and save it, then everything worked. Thanks for your time and help – blfuentes May 27 '20 at 07:03