Excel VBA ADO SQL连接错误 – 无法find对象

我从@Ryan Wildry那里得到了一个很好的答案,但是我想我会问一个关于相同代码的不同的问题:在这里。

背景信息

我有一个共享(networking/服务器)Excel模板文件既是input文件和数据源(虽然在不同的工作表)。 我们称之为Input.xltm

代码基本上在Input Sheet选取一个范围内的Input Sheet ,取前两个字母并从Code Sheetfind最接近的代码,然后用前五个结果填充UserForm列表框。

问题

问题出现在用户引发UserForm并且错误通常返回时:

Run-time error '-2147467259' The Microsoft Access database engine could not find the object 'C:\Users\user.name\Documents\Input1'. Make sure the object exists and that you spell its name and the path name correctly.......etc

我认为这可能与Excel在文件名后面加上一个数字有关,因为这是一个模板文件,尽pipe我不知道!

代码

这里是代码:

 Public MyConnection As New ADODB.Connection Public MyRecordset As New ADODB.Recordset Private Sub UserForm_Initialize() Dim ColumnName As String: ColumnName = "[Variant code]" Dim SearchStr As String: SearchStr = Left(Sheets("Input Sheet").Range("B4").Value2, 2) Dim dbstring As String dbstring = ThisWorkbook.FullName Application.ScreenUpdating = False If MyConnection.State <> adStateOpen Then With MyConnection .ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbstring & _ ";Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1';" .Open End With End If If MyRecordset.State = adStateOpen Then MyRecordset.Close MyRecordset.Open "Select top 5 " & ColumnName & " from [Code Sheet$] where " & ColumnName & _ " like '%" & SearchStr & "%'", MyConnection, adOpenForwardOnly, adLockReadOnly Me.ListBox1.Clear If Not MyRecordset.EOF Then MyRecordset.MoveFirst Application.ScreenUpdating = True Do Until MyRecordset.EOF Me.ListBox1.AddItem MyRecordset.Fields(0).Value MyRecordset.MoveNext Loop End Sub 

我只需要通过服务器访问文件的每个人都能够拾取正确的数据源(仅在下一张表中)并填充ListBox。

我会感谢任何build议! 谢谢

#UPDATE

我已经检查了,现在如果你打开(然后保存)实际的模板文件,所以在文件名后没有“1”,那么代码将按预期工作。 只有当模板正常打开,数字自动附加,它停止工作。

看起来你不会先为MyConnectionMyRecordset进行早期绑定。

你可以做一个迟到的绑定

步骤1。

更改

 Public MyConnection As New ADODB.Connection Public MyRecordset As New ADODB.Recordset 

 Public MyConnection As object Public MyRecordset As object 

第2步。

 Set MyConnection = createobject("adodb.connection") Set MyRecordset = createobject("adodb.recordset") 

之前If MyConnection.State <> adStateOpen Then