Split the main loop in two
Option Explicit
'declare & define Excel, Word dependecines
Dim ws As Worksheet
Dim msWord As Object
Dim objWord As Object
Dim docWord As Object
Dim fs A''#### Declarations | Declare variables to be used at module-level ####
s Object
'declare folder & file name
Dim folderName As String
Dim fileName As String
Dim liveNotifName As String
'global timers, counter & co
Dim i As Integer
Dim j As Integer
Dim lc As Integer
Dim k As Integer
Dim lastRow As Long
Dim employeeRows As Long
Dim wait As String
Dim notifWrite As Boolean
Dim firstEmployee As String
Dim lastEmployee As String 'assign only at the end of current conditional, within conditional (IF within FOR)!!!
Dim currentEmployee As String
Dim employeeName As String
Dim totalamount As String
Dim MessageBox As Integer
''----------------------------------------------------
''declare global variables for Word text & Excel cells
'declare global variables for Word text
Dim emailAddress_text As String
Dim employeeName_text As String
Dim expense_Meal_text As String
Dim expense_diem_text As String
Dim amount_meal_text As String
Dim amount_diem_text As String
Dim description_meal_text As String
Dim description_diem_text As String
Dim totalamount_diem_text As String
Dim totalamount_diem_currency_text As String
'declare global variables for Excel cells
Dim emailAddress_cell As String
Dim expense_Meal_cell As String
Dim expense_diem_cell As String
Dim amount_meal_cell As String
Dim amount_diem_cell As String
Dim currency_meal_cell As String
Dim currency_diem_cell As String
Dim description_diem_cell As String
Dim description_meal_cell As String
Dim analyst_cell As String
Dim analyst As String
Dim action_cell As String
Dim totalamount_diem_cell As String
Dim totalamount_diem_currency_cell As String
''----------------------------------------------------
'Declare global paths
Dim notifMainFolder As String
Dim notifTemplateDoc As String
Dim notifAnalystFolder As String
Dim notifTypeFolder As String
Dim notifEmployeeDoc As String
''#### Write Notifications with Word ####
Public Sub WriteNotifications_Education()
''----------------------------------------------------
''Set variables
'Directory & files variables
folderName = "Notifications"
fileName = "Education"
'Excel & Word application variables
Set ws = ThisWorkbook.Sheets("Audit")
Set msWord = CreateObject("Word.Application")
Set docWord = msWord.Documents.Add
'Set PhaseOne variables values for Word lookup text (tags)
emailAddress_text = "[emailaddress]"
employeeName_text = "[EmployeeName]"
expense_Meal_text = "[EM#]"
expense_diem_text = "[ED#]"
amount_meal_text = "[Amount_Meal]"
amount_diem_text = "[Amount_Diem]"
description_meal_text = "[Description_meal]"
description_diem_text = "[Description_diem]"
totalamount_diem_text = "[TotalAmount]"
totalamount_diem_currency_text = "[TotalAmount_Currency]"
'Set PhaseOne variables values for Excel cell values for correspoding Word text & processing
emailAddress_cell = "C"
expense_Meal_cell = "D"
expense_diem_cell = "M"
amount_meal_cell = "G"
amount_diem_cell = "P"
currency_meal_cell = "H"
currency_diem_cell = "Q"
description_diem_cell = "N"
description_meal_cell = "E"
analyst_cell = "AF"
analyst = "AF" 'for processing
action_cell = "AB" 'for processing
totalamount_diem_cell = "AC"
totalamount_diem_currency_cell = "AD"
''----------------------------------------------------
'Global timers, counters & co.
wait = "1"
notifWrite = False
lastRow = Range(emailAddress_cell & Rows.Count).End(xlUp).Row
firstEmployee = ws.Range(emailAddress_cell & CStr(2)).Value2
currentEmployee = firstEmployee
''----------------------------------------------------
''Set global paths
notifMainFolder = ActiveWorkbook.Path
notifTemplateDoc = notifMainFolder & "\" & fileName & ".docx"
notifAnalystFolder = notifMainFolder & "\" & ws.Range(analyst & CStr(2)).Value2
notifTypeFolder = notifAnalystFolder & "\" & fileName
notifEmployeeDoc = notifTypeFolder & "\" & currentEmployee & ".docx" '!!! Reinitiliaze at "create new Word file template for current employee" line
'Define liveNotifName - name of Word doc script is actively updating
liveNotifName = currentEmployee & ".docx"
''----------------------------------------------------
''Check if folder for current analyst exist. Create IF NOT.
Dim fdObj As Object
Application.ScreenUpdating = False
Set fdObj = CreateObject("Scripting.FileSystemObject")
If Not fdObj.FolderExists(notifAnalystFolder) Then
fdObj.CreateFolder (notifAnalystFolder)
End If
Application.ScreenUpdating = True
''----------------------------------------------------
''Check if folder for current notif type exist. Create IF NOT.
'Dim fdObj As Object
'Application.ScreenUpdating = False
Set fdObj = CreateObject("Scripting.FileSystemObject")
If Not fdObj.FolderExists(notifTypeFolder) Then
fdObj.CreateFolder (notifTypeFolder)
End If
Application.ScreenUpdating = True
''----------------------------------------------------
''Start first (main) For loop
For i = 2 To lastRow 'i must range from 2 to last row number
'define current employee (on current row)
currentEmployee = ws.Range(emailAddress_cell & CStr(i)).Value2
If (i = 2 And ws.Range(action_cell & CStr(i)).Value2 = fileName And ws.Range(emailAddress_cell & CStr(i)).Value2 = firstEmployee) Or (ws.Range(action_cell & CStr(i)).Value2 = fileName And currentEmployee <> lastEmployee) Then
'change global variable for notification written to reflect action
notifWrite = True
'initialize Word app resources inside loop, for each itereation
Set msWord = CreateObject("Word.Application")
Set docWord = msWord.Documents.Add
Application.wait (Now + TimeValue("0:00:0" & wait))
'##-- Whole section reiterates and check paths vs current analyst-action combo
'reitreate paths
'create new Word file template for current employee
notifMainFolder = ActiveWorkbook.Path
notifTemplateDoc = notifMainFolder & "\" & fileName & ".docx"
notifAnalystFolder = notifMainFolder & "\" & ws.Range(analyst & CStr(i)).Value2 '## Reinitilization to iterate for current analyst
notifTypeFolder = notifAnalystFolder & "\" & fileName '## Reinitilization to capture current analyst
notifEmployeeDoc = notifTypeFolder & "\" & currentEmployee & ".docx" '## Reinitilization to capture current analyst
''Re-Check if folder for current analyst exist. Create IF NOT.
Application.ScreenUpdating = False
Set fdObj = CreateObject("Scripting.FileSystemObject")
If Not fdObj.FolderExists(notifAnalystFolder) Then
fdObj.CreateFolder (notifAnalystFolder)
End If
Application.ScreenUpdating = True
''Re-Check if folder for current notif type exist. Create IF NOT.
'Dim fdObj As Object
'Application.ScreenUpdating = False
Set fdObj = CreateObject("Scripting.FileSystemObject")
If Not fdObj.FolderExists(notifTypeFolder) Then
fdObj.CreateFolder (notifTypeFolder)
End If
Application.ScreenUpdating = True
Set fs = CreateObject("Scripting.FileSystemObject")
fs.copyfile notifTemplateDoc, notifEmployeeDoc
'##-- Section ended and VBA know where to write
'open Word file
With msWord
.Visible = True
.ScreenUpdating = True
.Application.WindowState = xlMaximized
.Documents.Open (notifEmployeeDoc)
'reinitialie liveNotifName variable and activate corresponding Word instance
liveNotifName = currentEmployee & ".docx"
AppActivate liveNotifName & " - Word", True
'write employee email address
With msWord.Selection.Find
.Text = emailAddress_text
.Replacement.Text = ws.Range(emailAddress_cell & CStr(i)).Value2
.Forward = True
.Wrap = 2
.Execute Replace:=1
End With
'extract employeeName
employeeName = WorksheetFunction.Proper(Left(Range(emailAddress_cell & CStr(i)), InStr(Range(emailAddress_cell & CStr(i)), ".") - 1))
'write employee name
With msWord.Selection.Find
.Text = employeeName_text
.Replacement.Text = employeeName
.Forward = True
.Wrap = 2 'wdFindContinue (WdFindWrap Enumeration)
.Execute Replace:=1 'wdReplaceAll (WdReplace Enumeration)
End With
'ensure deselection & wait standard timer
Application.SendKeys "{DOWN}", True
'Application.wait (Now + TimeValue("0:00:0" & wait))
'count current employee rows
employeeRows = WorksheetFunction.CountIfs(Range(emailAddress_cell & "2:" & emailAddress_cell & lastRow), currentEmployee, Range(action_cell & "2:" & action_cell & lastRow), fileName)
''define new counters & vars
j = i
If employeeRows > 1 Then
'set selection start point
With msWord.Selection.Find
.Text = "Expense details:"
.Execute
End With
'minor loop to select text (to be copied)
For lc = 1 To 7
Application.SendKeys "^+{DOWN}", True
Next lc
'wait - essential for selection to happen!!
Application.wait (Now + TimeValue("0:00:0" & wait))
'copy selected text (to Clipboard)
msWord.Selection.Copy 'copy
'Application.wait (Now + TimeValue("0:00:0" & wait)) 'essential variable wait!!
Application.SendKeys "{DOWN}", True 'press "down arrow"
'Application.wait (Now + TimeValue("0:00:0" & wait)) 'essential variable wait!!
'loop to paste "Expense details" section based on employee rows (lines) number
For k = 1 To (employeeRows - 1)
Application.SendKeys "~", True 'press "enter" key
'Application.wait (Now + TimeValue("0:00:0" & wait)) 'essential variable wait!!
msWord.Selection.Paste 'paste
'Application.wait (Now + TimeValue("0:00:0" & wait)) 'essential variable wait!!
Next k
Application.SendKeys "^{HOME}", True 'go back to top of file
End If
'loop to write Excel-to-Word for employees with multiple lines
For j = j To lastRow
If ws.Range(emailAddress_cell & CStr(j)).Value2 = currentEmployee And ws.Range(action_cell & CStr(j)).Value2 = fileName Then
With msWord.Selection.Fin