VBA在尝试引用SQL数据库时不断出错

时间:2017-03-14 18:04:53

标签: sql excel vba excel-vba

我的程序基本上打开了任何.MDB文件,然后在电子表格中显示该文件,但是我不断收到此错误(尽管代码正常工作且文件在excel上打开)。

出现的错误是"运行时错误429,Active X组件无法创建对象"

这是我所拥有的代码,我将在我点击调试时突出显示的行上面写。

 Option Explicit

 Private Sub CommandButton1_Click()

 Dim strFileToOpen As String
 ChDir ThisWorkbook.Path
 strFileToOpen = Application.GetOpenFilename _
 (Title:="Please choose a file to open", _
 FileFilter:="All Files *.* (*.*),")


 Workbooks.Open fileName:=strFileToOpen
 frmMain.TextBox1.Text = strFileToOpen

 Exit Sub

 End Sub

 Private Sub CommandButton2_Click()
 Dim fileName As String
 Dim copyDestination As String
 Dim copyFile As String
 Dim fso

 If frmMain.TextBox1.Value = "" Then
 MsgBox "No File Selected"
 Else
 fileName = frmMain.TextBox1.Value

 copyDestination = ThisWorkbook.Path & "\Sales_Orders.mdb"

 Set fso = CreateObject("Scripting.FileSystemObject")

 fso.copyFile fileName, copyDestination, True

 Set fso = Nothing

 MsgBox "File copied to current workbook directory!"
 End If

 'SQL Statements

Dim db As Database
Dim qdef As QueryDef
Dim td As TableDef
Dim dbname As String

' Open the database. replace "c:\DBfile.mdb" with your
' database file name

'此行设置数据库= OPENDATABASE在我发出调试时突出显示

Set db = OpenDatabase(copyDestination)

' List the table names.
For Each td In db.TableDefs
' if you want to display also the system tables, replace the line
' below with:  List1.AddItem td.Name
   If td.Attributes = 0 Then ListBox1.AddItem td.Name
Next td
db.Close


 End Sub

 Private Sub CommandButton3_Click()
 Unload Me


 End Sub

如代码中所述,Set db = OpenDatabase(copyDestination)是我点击调试时突出显示的行。知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

OpenDatabase方法是Workbooks object的成员。如果没有对Workbooks对象的引用,则无法临时调用它。

Dim db as Object
Set db = Workbooks.OpenDatabase(copyDestination)

将您的db声明为对象,而不是数据库。