Good Afternoon forum community ? I have written codes to auto generate and save letters. Whenever I save the letters, I will include the name of letter and the company that I am generating for. The problem I came across is: if I generate two of the same letters for the same company, my code will auto replace the existing file. Is there any solution whereby the code can auto generate file name when there is an existing file with the same name? For example: The existing file is Nomination Letter - ABC Company. The second file I want to save it as Nomination Letter - ABC Company (2) instead of auto replacing the existing file. Thanks alot!!
VBA Code:
Private Sub NominationLetter()
Dim ws As Worksheet, msWord As Object
Dim currentRow As Long
Dim rowCount As Long
Dim lastRow As Long
Dim filename As String
Dim Path1 As String
Path1 = "C:\Edited Letters\"
Set wb = ThisWorkbook
Set ws = wb.Sheets("Details of Client")
Set msWord = CreateObject("Word.Application")
lastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
For currentRow = 2 To lastRow
If Not ws.Rows(currentRow).Hidden Then
filename = ws.Range("B" & currentRow).Value
With msWord
.Visible = True
.Documents.Open "C:\Nomination letter - template.docx"
.Activate
With .ActiveDocument.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "DATE"
.Replacement.Text = ws.Range("E" & currentRow).Value
.Forward = True
.Wrap = 1 'wdFindContinue (WdFindWrap Enumeration)
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=2 'wdReplaceAll (WdReplace Enumeration)
End With
With .ActiveDocument.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "COMPANY"
.Replacement.Text = ws.Range("B" & currentRow).Value
.Forward = True
.Wrap = 1 'wdFindContinue (WdFindWrap Enumeration)
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=2 'wdReplaceAll (WdReplace Enumeration)
End With
With .ActiveDocument.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "YEAR END"
.Replacement.Text = ws.Range("D" & currentRow).Value
.Forward = True
.Wrap = 1 'wdFindContinue (WdFindWrap Enumeration)
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=2 'wdReplaceAll (WdReplace Enumeration)
End With
msWord.ActiveDocument.SaveAs filename:=Path1 & "Nomination letter - " & filename & ".docx"
msWord.ActiveDocument.Close
rowCount = rowCount + 1
End With
End If
Next currentRow
msWord.Quit
End Sub