I want to create a Word form document that is completed daily and exports data to an Excel table I have in a sharepoint. My plan is to have a button at the bottom of the survey that runs a macro. This macro would send all data in the word form document to a new row of the excel to be stored. It's essentially the same as this: https://www.techrepublic.com/blog/10-things/10-steps-to-transferring-word-form-data-to-an-excel-sheet/ However, this guide is outdated and I run an issue at the "cnn.close" where it gives me an "Object Variable or With block variable not set" run-time error (91). Any help would be appreciated, I've been hitting my head for a few weeks trying to find a solution. Thank you!
Sub TransferToExcel()
'Transfer a single record from the form fields to an Excel workbook.
Dim doc As Document
Dim strCompanyName As String
Dim strPhone As String
Dim strSQL As String
Dim cnn As ADODB.Connection
'Get data.
Set doc = ActiveDocument 'ThisDocument
On Error GoTo ErrHandler
strCompanyName = Chr(39) & doc.FormFields("txtCompanyName").Result & Chr(39)
strPhone = Chr(39) & doc.FormFields("txtPhone").Result & Chr(39)
'Define sql string used to insert each record in the destination workbook.
'Don't omit the $ in the sheet identifier.
strSQL = "INSERT INTO [PhoneList$]" _
& " (CompanyName, Phone)" _
& " VALUES (" _
& strCompanyName & ", " _
& strPhone _
& ")"
Debug.Print strSQL
'Define connection string and open connection to destination workbook file.
Set cnn = New ADODB.Connection
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=E:\Examples\Sales.xlsx;" & _
"Extended Properties=Excel 8.0;"
.Open
'Transfer data.
.Execute strSQL
End With
Set doc = Nothing
Set cnn = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Number & ": " & Err.Description, _
vbOKOnly, "Error"
On Error GoTo 0
On Error Resume Next
cnn.Close
Set doc = Nothing
Set cnn = Nothing
End Sub