Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
Dim tbl As Word.Table
Dim xlApp As Object 'Excel.Application
Dim xlWbk As Object 'Excel.Workbook
Dim xlSht As Object 'Excel.Worksheet
Dim xlRng As Object 'Excel.Range
Dim strWbkName As String
'\\ Check if relevant info has been filled in Content Control
If Len(ContentControl.Range.Text) <> 4 Then Exit Sub
'\\ Set table reference
Set tbl = ThisDocument.Tables(1)
'\\ Define the source workbook name here
strWbkName = "Example Excel specs sheet.xlsx"
On Error Resume Next
'\\ Check if instance of Excel is running
Set xlApp = GetObject(, "Excel.Application")
If xlApp Is Nothing Then
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
End If
Set xlWbk = xlApp.Workbooks.Open(ThisDocument.Path & _
Application.PathSeparator & strWbkName)
If xlWbk Is Nothing Then
If xlApp.Visible = False Then xlApp.Quit
MsgBox "Source workbook not found!" & vbCrLf & _
"Please place it in the same directory as this word document" & vbCrLf & _
"Name should be : " & strWbkName, vbInformation
Exit Sub
End If
On Error GoTo 0
'\\ Now check through 2nd column and then change text accordingly
For i = 1 To tbl.Rows.Count
If InStr(tbl.Rows(i).Cells(2).Range.Text, ContentControl.Range.Text) > 0 Then
'\\ Loop through all sheets to locate info
For Each xlSht In xlWbk.Worksheets
Set xlRng = xlSht.Cells.Find(What:=ContentControl.Range.Text)
If Not xlRng Is Nothing Then
'\\ Currently your data is 2 columns offset to the number
tbl.Rows(i).Cells(3).Range.Text = xlRng.Offset(0, 2).Value
Exit For '\\ Found and updated info so exit
End If
Next xlSht
End If
Next i
'\\ After processing reset
If xlApp.Visible = False Then
xlApp.Quit
Else
xlWbk.Close
End If
'\\ Release variables
Set xlApp = Nothing: Set xlWbk = Nothing: Set xlSht = Nothing: Set xlRng = Nothing
End Sub