0

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

谢谢!

这是我的代码:

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
4

1 回答 1

1

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

您必须打开 MDB 文件:

Dim db As New Access.Application

db.OpenAccessProject filepath

用于db检索表:

db.TableDefs....
于 2013-08-07T09:31:13.880 回答