Search code examples
excelvbams-wordmailmerge

How to filter mail merge source data according to user input?


Four days ago I asked a mail merge question and got a great answer, but I have people complaining about getting a popup to confirm the SQL connection. They just have to click Yes, so IMO, this is not a critical issue. My question is, how hard would it be to eliminate the SQL connection confirmation popup by connecting to the Excel source file from within my macro? I tried and have it working OK as long as I'm pulling the entire range. Problem is, I don't want all the source records, I want only one, the one end-user selects by typing LoginID in Inputbox. LoginID is a column in the spreadsheet, All_Users$ tab. As soon as I put:

WHERE LoginID = "" + myKey + """ + ",

in the SQLStatement, I get error: Error has occurred: External table is not in the expected format.

I've looked up dozens of articles about mail merge in this forum and built my code bit by bit. I'm missing this last part about the filter.

Here's my code:

Sub MergetoNewDoc()
Dim wrdObj As Object, wrdDoc As Object
Dim strFile As String, myKey As String
Dim mySource As String: mySource = "C:\Users\jtorres\desktop\LetterMemoDB.xlsx"

Set wrdObj = CreateObject("Word.Application")
myKey = InputBox("Enter LoginID:")

With wrdObj
  .Visible = False
  .DisplayAlerts = False
  Set wrdDoc = .Documents.Open("C:\Users\jtorres\desktop\NewLetterTemplate.docx", False, True, False, , , , , , , , False)
  With wrdDoc
    With .MailMerge
      .MainDocumentType = wdFormLetters
      .Destination = wdSendToNewDocument
      .SuppressBlankLines = True
      .OpenDataSource Name:=mySource, ReadOnly:=True, AddToRecentFiles:=False, _
        LinkToSource:=False, Connection:="Provider=Microsoft.ACE.OLEDB.14.0;User ID=Admin;" & _
        "Data Source=mySource;Mode=Read;Extended Properties=""HDR=YES;IMEX=1"";", _
        SQLStatement:="SELECT * FROM `All_Users$` WHERE LoginID = "" + myKey + """ + ","
      .Execute
    End With
    .Close 0
  End With
End With
Set wrdDoc = Nothing: Set wrdObj = Nothing
End Sub

Solution

  • Try

    SQLStatement:="SELECT * FROM [All_Users$] WHERE LoginID = '" & myKey & "'"