【发布时间】:2021-03-03 17:43:03
【问题描述】:
我在 Excel 365 > Visual Basic 编辑器中使用以下代码来尝试确定用于创建旧数据库的 MS Access 版本。该代码适用于我作为测试创建的较新的.accdb 数据库。据我所知,旧数据库最初是在 Access 97 中编写/设计的,但我想确定一下。
Public Sub GetAccessFormat()
' Attempt to determine the format of an Access database
' Note: Can Access 16.0 (Office 365) read databases from Office 2013 and earlier?
On Error GoTo Error_NotAccessDatabase
Dim fileName As String
'fileName = "C:\Tmp\old.mdb" ' Fails
fileName = "C:\Tmp\new.accdb" ' Works
If IsEmpty(Dir(fileName)) Then
MsgBox "Could not find: " & fileName
Exit Sub
End If
' Open the database
Dim objAccess As Object
Set objAccess = CreateObject("Access.Application") ' Is this the problem?
objAccess.OpenCurrentDatabase fileName
objAccess.Visible = False
' Get the file format
Dim fileFormat As Integer
fileFormat = objAccess.CurrentProject.FileFormat ' Gets here and fails for .mdb (returns "12" for the .accdb)
Dim strAccessFormat As String
strAccessFormat = "Your database is: "
Select Case fileFormat
Case 2
strAccessFormat = (strAccessFormat & "Microsoft Access 2")
Case 7
strAccessFormat = (strAccessFormat & "Microsoft Access 95")
Case 8
strAccessFormat = (strAccessFormat & "Microsoft Access 97")
Case 9
strAccessFormat = (strAccessFormat & "Microsoft Access 2000")
Case 10
strAccessFormat = (strAccessFormat & "Microsoft Access 2002")
Case 11
strAccessFormat = (strAccessFormat & "Microsoft Access 2003")
Case 12
strAccessFormat = (strAccessFormat & "Microsoft Access 2007")
Case 14
strAccessFormat = (strAccessFormat & "Microsoft Access 2010")
Case 15
strAccessFormat = (strAccessFormat & "Microsoft Access 2013")
Case 16
strAccessFormat = (strAccessFormat & "Microsoft Access 2016/9")
Case Else
strAccessFormat = "Unknown Access file format"
End Select
' Close database and display the format information
objAccess.CloseCurrentDatabase
strAccessFormat = (strAccessFormat + " (" & fileFormat & ".0)")
MsgBox strAccessFormat
Exit Sub
Error_NotAccessDatabase:
' Unable to open the database (not Access or not supported by this version of Office?)
MsgBox "Unable to open as Access database: " & strFile & ", Error: " & Err.Description
Exit Sub
End Sub
错误文本是“您输入的表达式引用了一个已关闭或不存在的对象。” (数据库确实存在,没有在另一个应用程序中打开并且数据库上没有锁)
我们安装了 Office 365(带有 Access 16.0),所以我认为问题出在 Set objAccess = CreateObject("Access.Application"),因为我 PC 上的“访问应用程序”将无法读取旧格式的访问数据库。
这是正确的吗?是否有一种解决方法来确定旧 Access 数据库的文件格式?
【问题讨论】:
-
您不需要像主机那样使用后期绑定声明。它已经被你使用它的性质加载了。删除
objAccess并简单地替换为Application -
请注意,Access_2013 及更高版本绝对拒绝从 Access_97 及更早版本打开 .mdb 文件。
-
@HackSlash:不确定我是否遵循。
Application有ActiveCell这样的成员,但没有CurrentProject或FileFormat成员或属性。 -
@AlainD,请参阅我的答案中的测试代码。如果您看到
ActiveCell,那么听起来您正在使用 Excel。您的标签上写着ms-access,所以我假设您使用 Access 作为主机来运行 VBA。如果不是预期的,请在您的问题中说明您使用的 VBA 主机。 -
@HackSlash:是的 Excel...除了 Microsoft Office 产品之外,还有其他
VBA主机吗?我确实澄清了我使用的是 Office 365,问题中是否缺少某些内容?