Hello,
I am trying to insert the file after finding text. After inserting first file it will add subsequent files after. However, I am having issues with inserting subsequent files, as it will insert it after the found text. Can anyone help?
Thanks
Code:
Sub InsertSpecs(dWS As Worksheet, findText As String, subPath As String, wdRange As Object, wdApp As Object, chkSpec As String, c As Long)
Set wdApp = CreateObject("Word.Application")
Set compDoc = wdApp.Documents.Open("C:\Users\nguye\OneDrive\Desktop\22 SPECS\SP_TEMPLATE_A10-21-22__2022.docx") 'SSP Template filepath
wdApp.Visible = True
wdApp.ActiveWindow.View.ShowHiddenText = True
Set wdRange = compDoc.Range 'set the search range to include headings
Dim bfound As Boolean, srng As Object, insertRange As Object, looprange As Range
Dim filePath As String, currentFormat As Long
bfound = False 'set bfound to False by default
filePath = subPath & dWS.Range("E" & c).Value 'build file path
If Dir(filePath) <> "" Then 'check if file exists in folder
With wdRange.Find
.ClearFormatting
.Text = findText
.Forward = True
.Wrap = wdFindContinue
bfound = .Execute(Forward:=True)
End With
If bfound Then
'set srng to the found range and move it down one line
Set srng = wdRange.Duplicate
srng.Collapse wdCollapseEnd
srng.MoveStartUntil vbCr
srng.MoveStart wdCharacter, 1
'set insertRange to the end of srng
Set insertRange = srng.Duplicate
insertRange.Collapse wdCollapseEnd
'insert a new paragraph and the file content
insertRange.InsertParagraphAfter
insertRange.InsertFile filePath, "", False, False, False
insertRange.Select
c = c + 1
Do Until chkSpec = ""
If chkSpec = "True" Then
filePath2 = subPath & dWS.Range("E" & c).Value
If Dir(filePath) <> "" Then
'insert a next spec
Selection.InsertFile filePath2, "", False, False, False
Selection.MoveEnd
c = c + 1
ElseIf chkSect = "False" Then
c = c + 1
End If
i = c + 1
End If
Loop
End If
End If
End Sub