如何在不打开mdb文件的情况下使用vba访问Access中的表?

时间:2013-08-07 09:21:45

标签: vba ms-access

如果该字段不存在,我正在尝试使用VBA将字段添加到mdb文件中的表。如果我在Access中打开mdb文件,并运行VBA代码,它工作正常。但是,如果我clode Access,我将遇到'错误3265:此集合中找不到项。' at'With Access.Application.DBEngine(0)(0).TableDefs(“Contract”)'stage。

谢谢!

这是我的代码:

Sub ResetDB()
Dim nlen As Long

MsgBox ("Select the Access Database using this browse button")
    NewFN = Application.GetOpenFilename(FileFilter:="mdb.Files (*.mdb), *.mdb", Title:="Please select a file")

    If NewFN = False Then
        ' They pressed Cancel
        MsgBox "Try Again if database needs to be reset"
        Application.DisplayAlerts = False
        'ActiveWorkbook.Close
        Application.DisplayAlerts = True
        Exit Sub
    Else
        ActiveWorkbook.Unprotect ("12345")
        Sheets("Version").Visible = True
        Worksheets("Version").Unprotect (strPW)
        Range("Database").Value = NewFN

    'On Error GoTo Failed ' I comment this line just to see where the error is
    ' following line is when the error occurs
        With Access.Application.DBEngine(0)(0).TableDefs("Contract")
        .Fields.Refresh
        nlen = Len(.Fields("Industry_Type").Name)
        If nlen > 0 Then Sheets("Instructions").Range("a1") = 1 ' do nothing
        End
        End With
Failed:
    If Err.Number = 3265 Then Err.Clear ' Error 3265 : Item not found in this collection.
    With Access.Application.DBEngine(0)(0).TableDefs("Contract")
    .Fields.Append .CreateField("Industry_Type", dbLong)
    End With
    End

    End If
End Sub

1 个答案:

答案 0 :(得分:1)

如果Access已关闭,您将无法使用它。

您必须打开MDB文件:

Dim db As New Access.Application

db.OpenAccessProject filepath

使用db来检索表格:

db.TableDefs....