Noob Coder
New Member
- Joined
- Nov 21, 2019
- Messages
- 3
I have a couple of excels I am messing around with practicing VBA. They all at have code to mail merge. On one excel I subtract the row number from the row where my headers are. For example my headers are on row 22 and my data starts at row 23. So I subtract 22 from the row number and it begins the mail merge from there (or it only starts to count records from there. I am unsure). So if I have 3 rows of data that would be row 23 to 25. The code subtracts 22 and I am left with 3 records to mail merge. I am learning VBA so I have a hard time figuring out the code I need to only do the last row. Here is my mail merge code that I put together from online sources:
VBA Code:
Private intakeForm As String
Private wdApp As Word.Application
Public newFilePath As String
Public newFolderName As String
Sub MailMergeAutomation()
Dim filePath As String
filePath = ThisWorkbook.Path & "\" & "Forms" & "\"
Dim wdDoc As Word.Document
Dim TargetDoc As Word.Document
Dim recordNumber As Long
Dim selRow As Range
Set selRow = Selection
intakeForm = "New Intake Form"
recordNumber = selRow.Row
Set fso = New Scripting.FileSystemObject
Set wdApp = New Word.Application
If wdApp Is Nothing Then
Set wdApp = New Word.Application
End If
Set fso = New FileSystemObject
With wdApp
.Visible = False
Set wdDoc = .Documents.Open(filePath & intakeForm)
wdDoc.MailMerge.MainDocumentType = wdFormLetters
wdDoc.MailMerge.OpenDataSource _
Name:=ThisWorkbook.Path & "\" & ThisWorkbook.Name, _
AddToRecentFiles:=False, _
Revert:=False, _
Format:=wdOpenFormatAuto, _
Connection:="Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";Mode=Read", _
SQLStatement:="SELECT * FROM [Headers]"
With wdDoc.MailMerge
.Destination = wdSendToNewDocument
With .DataSource
.FirstRecord = recordNumber - 22
.LastRecord = recordNumber - 22
'.ActiveRecord = .Ac
.LastRecord = recordNumber - 22
End With
.Execute Pause:=False
wdApp.Visible = False
Set TargetDoc = wdApp.ActiveDocument
TargetDoc.SaveAs2 Filename:=ThisWorkbook.Path & "\" & Sheet1.Cells(recordNumber, 3) & " " & "- intakeForm.docx"
wdDoc.Close SaveChanges:=False
End With
End With
Set wdDoc = Nothing
wdApp.Quit
Set wdApp = Nothing
End Sub