问题
I've been working on this for the past 6 hours and I'm getting a frustrating error. For now, I want to add a combo box into my blank word document and populate it with a data from a field in a table I created in Access. I'm using Visual Studio 2015 as my IDE and the Word 2013 Document Template.
ERROR
An exception of type 'System.Runtime.InteropServices.COMException' occurred in WordInvoice.dll but was not handled in user code
Additional information: Provider cannot be found. It may not be properly installed.
My Database Table
ID Employee Amount
1 Danny $100.00
2 Andy $200.00
3 Dixon $50.00
4 James $250.00
MY CODE
Imports System.Diagnostics
Imports Microsoft.Office.Interop.Word
Public Class ThisDocument
Private Sub ThisDocument_Startup() Handles Me.Startup
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
cnn.Open("Provider=Microsoft.Jet.OLEDB.4.0;" &
"Data Source=C:\Users\Danny\Documents\Employee Records1.accdb")
rst.Open("SELECT Employee FROM Payroll;", cnn, ADODB.CursorTypeEnum.adOpenStatic)
rst.MoveFirst()
Dim ccList As ContentControl
ccList = ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlComboBox)
ccList.Title = "Select a Employee"
ccList.SetPlaceholderText(,, "Please Select a Employee")
Do While Not rst.EOF
ccList.DropdownListEntries.Add(rst.Fields(0).ToString)
rst.MoveNext()
Loop
rst.Close()
End Sub
Private Sub ThisDocument_Shutdown() Handles Me.Shutdown
End Sub
End Class
WHAT I'VE TRIED
From some advice I read, I changed by 'Target CPU': from any PC
to x86
. However, this time I received this error from Word upon starting up.
回答1:
Haven't been praticing for a while but, if my memories are correct, this should work :
Public Class ThisDocument
Private Sub ThisDocument_Startup() Handles Me.Startup
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
cnn.Open("Provider=Microsoft.Jet.OLEDB.4.0;" &
"Data Source=C:\Users\Danny\Documents\Employee Records1.accdb")
rst.Open("SELECT Employee FROM Payroll;", cnn, ADODB.CursorTypeEnum.adOpenStatic)
rst.MoveFirst()
Dim ccList As ContentControl
ccList = ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlComboBox)
ccList.Title = "Select a Employee"
ccList.SetPlaceholderText(,, "Please Select a Employee")
Set ccList.RowSource=rst
End Sub
...
I'm not able to test it, this may require a bit of tweaking... but RowSource have always been the best way (as far as I know) to feed ListBox/ComboBox with DB rows.
This supports a lot of sources like ADO & DAO Recordsets, Arrays...
回答2:
You need to install the x64 Microsoft Access Database Engine 2010 Redistributable and change your connection string to Provider=Microsoft.ACE.OLEDB.12.0
来源:https://stackoverflow.com/questions/32573294/trying-to-connect-a-combobox-in-word-to-a-database-in-access-using-visual-basic