从Excel打开ADODB连接 – 错误424

我试图创build一个通用的函数来返回一个打开的连接。 但是,当我将函数设置为连接对象时,代码在最后一行出现错误。 需要一些方向来实现这一目标。 谢谢!

'' ' Function to open an ADODB connection and return the connection object ' @param strDBPath string containing full path to database of interest ' @param strUserID optional string containing user name to use when establishing the connection (default: vbNullString) ' @param strPassword optional string containing password to use when establishing the connection (default: vbNullString) ' @param intOptionsEnum optional integer to open the connection synchronously (-1) (defualt) - 16 to open connection asynchronously ' @return Object containing opened ADODB connection ' @remarks Have only tested this on .mdb database (not .accdb) Public Function vfnc_StartConnection( _ strDBPath As String, _ Optional strUserID As String = vbNullString, _ Optional strPassword As String = vbNullString, _ Optional intOptionsEnum As Integer = -1 _ ) As Object Dim objConn As Object: Set objConn = CreateObject("ADODB.connection") Dim strDataSource As String: strDataSource = "Data Source=" & strDBPath & ";" '#If VB7 And Win64 Then strProvider = "Provider=Microsoft.ACE.OLEDB.12.0; " '#Else 'strProvider = "Provider=Microsoft.Jet.OLEDB.4.0; " '#End If Set vfnc_StartConnection = objConn.Open(strProvider & strDataSource, strUserID, strPassword, intOptionsEnum) 'Error occurs here End Function 

Connection对象的Open方法不返回对象。 因此设置objConn.Open是不合适的。

你可能只想返回打开的objConn对象本身,即

  'Open the connection objConn.Open strProvider & strDataSource, strUserID, strPassword, intOptionsEnum 'Now that the connection has been opened, return the connection to the calling routine Set vfnc_StartConnection = objConn 

这里是我采取的,使用ConnectionString本质,部分基于YowE3K的答案。

 Public Function vfnc_StartConnection(strDBPath As String, Optional strUserID As String = "admin", Optional strPassword As String = vbNullString, Optional intOptionsEnum As Integer = -1) As ADODB.Connection Dim objConn As ADODB.Connection Set objConn = New ADODB.Connection Dim strDataSource As String Dim strprovider As String strDataSource = "Data Source=" & strDBPath & ";" strprovider = "Provider=Microsoft.ACE.OLEDB.12.0; " objConn.ConnectionString = strprovider & strDataSource & ";User ID=" & strUserID & ";Password=" & strPassword & ";" objConn.Open Set vfnc_StartConnection = objConn End Function