Automated MailMerge to Select Source File - vba

I created a Word (2022) mailmerge document. Later I changed the .docx to a .docm so I could do some post-mailmerge processing on the generated output. Now I'd like to use VBA to allow selection of the source data file, but I wasn't able to make that work.
Then I found [https://stackoverflow.com/questions/61547489/automated-word-vba-mailmerge], which described exactly what I'm looking to perform in VBA. In my mailmerge document VBA I now have:
Private Sub Document_Open()
' Application.ScreenUpdating = False
Dim StrMMSrc As String
With Application.FileDialog(FileDialogType:=msoFileDialogFilePicker)
.Title = "Data Source Selector"
.AllowMultiSelect = False
.Filters.Add "Documents", "*.xls; *.xlsx; *.xlsm", 1
.InitialFileName = ""
If .Show = -1 Then
StrMMSrc = .SelectedItems(1)
Else
GoTo ErrExit
End If
End With
With ActiveDocument.MailMerge
.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 'Students'"
End With
ErrExit:
Application.ScreenUpdating = True
When I open the merge document I can step through the Document_Open code in VBA. The FileDialog works correctly, showing me the folder C:\Gld\RT\Office Database, and I select file "Database 2022-23.xlsx". Variable StrMMSrc is correctly set to the file I selected, "C:\Gld\RT\Office Database\RT Database 2022-23 Test.xlsx". But then it pops up a window "Select Table" showing no tables. If I drop down Workbook, it shows me 2 old Excel documents and a document named "C:\Gld\RT\Office Database.xls", which doesn't actually exist. Any idea as to why it's confusing the "Office Database" folder with a non-existent "Office Database.xls" document?

Jonsson's comments answer the question accurately.
I don't know what went wrong the other day, but using the syntax
SELECT * FROM [Students$] Order by [Grade] ASC, [Last Name] ASC, [First Name] ASC
worked correctly today.
Thanks so much, Jonsson, for your time and effort in helping me.

Related

Need to call other Word macros in mass update tool

Quick summary: I need to call additional macros to modify documents inside of an existing code that mass converts Word files to PDF (if possible).
Longer story: I have code from a long time ago (credit to wherever I found it a decade ago). It uses a file dialog to allow selecting multiple files, and then converts those selected files to PDF. I have almost 1,800 Word documents that I need to process (using the code #timothyrylatt helped with here: How to find table column, then move down and replace the cell's content IF it is "N/A") and then convert to PDF afterwards. I tried using the 'Call' feature to call the "Demo" macro, and changing the save settings but the files only convert to PDF without calling the other "Demo" macro. I tried calling it in different areas as well, but to no avail.
Note: If it is not possible to add to this existing code, is there still a way to at least select the multiple files, run the Demo macro, then save and close in a similar manner?
Thank you in advance for any assistance!
Sub MassUpdate()
Dim wDoc As Word.Document
Dim FoundFile As Variant
Dim wDialog As FileDialog
Set wDialog = Application.FileDialog(FileDialogType:=msoFileDialogFilePicker)
wDialog.AllowMultiSelect = True
If wDialog.Show <> -1 Then
Exit Sub
End If
For Each FoundFile In wDialog.SelectedItems
Set wDoc = Documents.Open(FoundFile, ReadOnly:=False, Visible:=False)
Call Demo
wDoc.ExportAsFixedFormat _
OutputFileName:=wDoc.Path & "\" & Left(wDoc.Name, InStrRev(wDoc.Name, ".")) & "pdf", _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, Range:=wdExportAllDocument, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
wDoc.Close SaveChanges:=True
Next
Dim Answer
Answer = MsgBox("Update more files?", vbYesNo, "Run Macro?")
If Answer = vbYes Then
Call MassUpdate
End If
End Sub
I would suspect that the two routines may be targeting different documents. Try modifying your Demo routine to take a document as an input argument:
Sub Demo(targetDoc as Document)
Application.ScreenUpdating = False
Dim r As Long, c As Long
With targetDoc.Range
You would then modify the Call line to (there is no need to use Call):
Demo wDoc

Late Bind on msoFileDialogFilePicker

I am self taught in VBA, which is probably the worst kind, and I still consider myself a novice. There are some things I just can't understand and this site has been a godsend. This code is not my own, so I barely understand what it is doing, which makes it difficult to alter. It's been working for the past two years. The company is now slowly upgrading computers and we now have some running Office 2010 and some running 2013. That means I can no longer use Office Tool references in my code, because it breaks between systems. So long story short, I need to do a late binding on this bit of code and I have no idea how.
I get an error on msoFileDialogFilePicker and msoFileDialogViewList
Please Overflow community, HELP!
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False 'Select only one file
.Title = "Locate file" 'Set dialog title
.ButtonName = "Choose" 'Set the button caption
.Filters.Clear 'Make sure the filter list is clear
.InitialFileName = "\\PUSNBF02\common\Admin\New EA's\" 'Initial file search location
.InitialView = msoFileDialogViewList 'View as list
'Show the dialog and test the return
If .Show = 0 Then 'didn't pick a file - exit sub
Exit Function
Else
'Should be only one file name - grab it
SourceFile = Trim(.SelectedItems(1)) 'Full path of file
strSource = SourceFile
strSourcePath = Left(strSource, InStrRev(strSource, "\"))
strSourceFileName = Mid(strSource, InStrRev(strSource, "\") + 1)
strSourceExtension = Right(strSource, Len(strSource) - InStrRev(strSource, "."))
'Debug.Print strSourceExtension
End If
End With
Just replace them with the appropriate numbers.
You can look up these numbers either by typing ?msoFileDialogFilePicker in the immediate window if you have it early-bound, by looking them up in the object browser, or, plain Google.
The corresponding number for msoFileDialogFilePicker is 3, so you can replace it with that:
With Application.FileDialog(3)
'...
.InitialView = 1 'View as list
'...

Run-time error '2522' - The action or method requires a File Name argument

I recently received a new laptop at work with Windows 10 (64-bit machine). I'm fairly new to VBA/Access and figured out how to get Access to operate on the 64-bit machine.
I am now encountering an issue with a browse button where a user (myself) clicks on a button that then directs me to choose the file. I did not create this database so I am just a secondary user.
Now when I click on it I am receiving a VBA error: Run-time error '2522' - The action or method requires a File Name argument
This is the argument that it is pointing to: DoCmd.TransferSpreadsheet acImport, , "tempDemographics", strInputFileName, True
Any idea on what can fix this? I've included the full code below:
Dim strFilter As String
Dim strInputFileName As String
strFilter = ahtAddFilterItem(strFilter, "Excel Files (*.xls*)", "*.xls*")
strInputFileName = ahtCommonFileOpenSave( _
Filter:=strFilter, OpenFile:=True, _
DialogTitle:="Select Facilities Extract...", _
Flags:=ahtOFN_HIDEREADONLY)
DoCmd.TransferSpreadsheet acImport, , "tempDemographics", strInputFileName, True
UPDATE:
I tried running a breakpoint at the DoCmd.TransferSpreadsheet..... line. Once I do that and it takes me right back to the VBA dialogue.
Also, here is the full code for reference:
Private Sub cmdDemographics_Click()
'turn off warnings
DoCmd.SetWarnings False
'delete current Demographics data
DoCmd.RunSQL "DELETE * FROM tblDemographics"
'Upload Facilities Extract into tempTable
Dim strFilter As String
Dim strInputFileName As String
strFilter = ahtAddFilterItem(strFilter, "Excel Files (*.xls*)", "*.xls*")
strInputFileName = ahtCommonFileOpenSave( _
Filter:=strFilter, OpenFile:=True, _
DialogTitle:="Select Facilities Extract...", _
Flags:=ahtOFN_HIDEREADONLY)
DoCmd.TransferSpreadsheet acImport, , "tempDemographics", strInputFileName, True
'create Demographics table (include SupervisorID)
DoCmd.OpenQuery "AppendDemographics"
'generate and display exception report
DoCmd.OpenReport "rptExceptions", acViewPreview
'remove tempDemographics Data
DoCmd.RunSQL "DELETE * FROM tempDemographics"
'add in X sitecode for unmapped TNPs
addXSiteCode
MsgBox "Demographics File Imported Sucessfully"
'turn warnings back on
DoCmd.SetWarnings True
End Sub
To clarify:
The issue I am having is during the import. The Import is pointing to a macro button which I click on, then it will bring up a dialogue box to point to the excel file that I wish to import. As of right now when I click on the macro button I am receiving the run-time error 2522 message.

Why won't this loop to add CustomDocumentProperties work?

I'm trying to add a few custom document properties to a folder of word documents.
I know that the loop itself works fine, because I used the same loop with different code to modify and then update pre-existing custom document properties.
The code to add custom document properties also works, I tested it by running it in it's own macro for a single document, which worked fine.
Since the loop works and the code within the loop also works, I just can't figure out what's wrong with it.
Here's the code:
Sub add_custom_docproperties()
Dim file
Dim path As String
Dim filepath As Variant
filepath = InputBox("Please enter the filepath for the files you want to
update.", "Input Filepath", "Copy filepath here...")
Select Case StrPtr(response)
Case 0
endednotification = MsgBox("The macro has been ended.", , "Notification")
Exit Sub
Case Else
End Select
path = filepath & "\"
file = Dir(path & "*.*")
'Application.ScreenUpdating = False
Do While file <> ""
Documents.Open FileName:=path & file
Check = MsgBox(path & file, , "Check")
ActiveDocument.CustomDocumentProperties.Add Name:="firstdocprop",
_LinkToContent:=False, Type:=msoPropertyTypeString, Value:="The First One"
ActiveDocument.CustomDocumentProperties.Add Name:="seconddocprop",
_LinkToContent:=False, Type:=msoPropertyTypeString, Value:="Second"
ActiveDocument.CustomDocumentProperties.Add Name:="thirddocprop",
_LinkToContent:=False, Type:=msoPropertyTypeString, Value:="Third"
'original example from:
'https://msdn.microsoft.com/en-us/vba/office-shared-vba
/articles/documentproperties-add-method-office
ActiveDocument.Save
ActiveDocument.Close
'set file to next in Dir
file = Dir()
Loop
'Application.ScreenUpdating = True
MsgBox "The macro is complete."
End Sub
As you can see I have a comment there with the first example I tried from msdn, which I modified.
Thanks in advance for any help, even if you could just point me to a resource explaining where I've gone wrong or something like that.
Word does not recognise the changes to the CustomDocumentProperties as being sufficiently important to actually save the document when you execute the Save command - unless you had made other changes it just decides to ignore the Save.
You can force a save by telling Word that the document has not been saved since it was last changed:
ActiveDocument.Saved = False
ActiveDocument.Save
ActiveDocument.Close

Match SaveAs2 Dialog File Type To Application.FileDialog

Say you want to have a button that the user can click and save a copy of the current file as a PDF(Documentation):
Application.ActiveDocument.SaveAs2 fileName:="fileName.pdf", FileFormat:=wdFormatPDF
This works fine, the user is presented with a save dialog, selects a location and the file is saved, however a few things are not correct:
The type displayed does not match what was specified in the VBA, how can this be correct? It still saves as type "PDF" without issue, even after showing "DOCX" as the file type in the "Save as Type" drop down. Also the "fileName.pdf" is not placed in the "File Name" box, its as if the dialog box is unaware of the options set in the VBA code(This same issue is also referenced in this post).
UPDATE 1
After taking a second look at my code I now realize that the SaveAs2 Method was not displaying the dialog menu, the correct version of the code(simplified) can be described as:
Dim selected As String: selected = Application.FileDialog(msoFileDialogSaveAs).Show()
Dim filePath As String
If selected <> 0 Then
filePath = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
Application.ActiveDocument.SaveAs2 fileName:=Split(filePath, ".")(0), FileFormat:=wdFormatPDF
End If
So then the real question(I guess) is how do you get "Application.FileDialog" to display the proper type you wish to save in under the "Save as type" drop down, and this has already been answered by #PatricK. Thanks everyone for the help, I apologize for the initial confused nature of this question.
I am surprised for SaveAs2 will bring you a prompt to be honest - Only a new document and .Save will bring you that prompt.
If you want to get something similar to that prompt, you use Application.FileDialog with type msoFileDialogSaveAs.
Use this code below (perhaps as an AddIn suits more):
Option Explicit
Sub MySaveAs()
Dim oPrompt As FileDialog, i As Long, sFilename As String
Set oPrompt = Application.FileDialog(msoFileDialogSaveAs)
With oPrompt
' Find the PDF Filter from Default Filters
For i = 1 To .Filters.Count
'Debug.Print i & " | " & .Filters(i).Description & " | " & .Filters(i).Extensions
' Locate the PDF filter
If InStr(1, .Filters(i).Description, "PDF", vbTextCompare) = 1 Then
.FilterIndex = i
Exit For
End If
Next
' Change the title and button text
.Title = "Saving """ & ActiveDocument.Name & """ to PDF format"
.ButtonName = "Save to PDF"
' Default name
.InitialFileName = ActiveDocument.Name
' Show the Prompt and get Filename
If .Show = -1 Then
sFilename = .SelectedItems(1)
Debug.Print "Final filename: " & sFilename
' Save the file as PDF
ActiveDocument.SaveAs2 sFilename, wdFormatPDF
End If
End With
Set oPrompt = Nothing
End Sub
Screenshot sample: