【问题标题】:If table not in Access database from Excel VBA如果表不在 Excel VBA 的 Access 数据库中
【发布时间】:2013-11-27 12:57:53
【问题描述】:

如何通过 Excel vba 检查给定表(称为Items)是否在特定的 Access 数据库中。

我已经通过 Excel vba 建立了从 Excel 工作表到两个不同数据库 [A] 和 [B] 的连接,并且我的其他代码工作正常。

到目前为止,我能在网上找到的最接近的是:

If IsNull(DLookup("[Name]", "MSysObjects", "[Name]='Items'")) Then

此代码未指定我要搜索的数据库。只有在数据库 [B] 中找不到表 Items 时,我才能编写一条语句来运行?这段代码怎么写?

引用数据库没有问题。我的大部分代码是从 Excel 运行的 SQL,并且我能够在特定于每个数据库的字段中引用各种条目。我只是在寻找一行写着“如果 this 表在 this 数据库中不存在,则创建一个具有 that 名称的表”。是否有我可以编写的 SQL 字符串,甚至是 try...catch 方法?

任何帮助将不胜感激

【问题讨论】:

  • 我认为 DLookup 函数是 Access 特有的。你能展示你是如何从 Excel 中“建立连接”到 Access 数据库的吗?
  • 查看stackoverflow.com/questions/9083232/… 中给出的代码 - 它显示了 Excel 如何引用特定数据库(并且没有理由使用该方法不能拥有两个数据库)。但它不使用DLookup...
  • 谢谢弗洛里斯。我更新了我的问题。

标签: excel ms-access vba


【解决方案1】:

您可能可以使用On Error 技术(它有点像try...catch,除了后者在VBA 中不存在)。例如:

On Error GoTo whoa
Set db = OpenDatabase(DBFullName) ' use the name of [A] or [B] here.
Set rs = db.OpenRecordset( *** your expression to get something from db *** )
' if you get past this line, then reading the data went OK
MsgBox "Everything is fine"
' it is possible that the above will not throw an error, but returns something "empty"
' I would put a breakpoint in the code and step through, then examine `rs`
' both for the case where the table exists, and where it doesn't
Exit Function
whoa:
MsgBox "Something went horribly wrong: error is " & Err.Description
' this is where you would go if you were not able to get the data

很明显,您会为 [A] 和 [B] 都这样做,以找出表存在的位置(如果有的话)。我的机器上没有 Access,所以我无法轻松地为您测试,抱歉。

【讨论】:

  • 非常感谢,弗洛里斯!我对此稍作修改,以便代码尝试创建表。如果创建不起作用,则假设表存在,则继续执行代码。一切正常。
  • 你可以在 VBA 中模拟一个 TRY CATCH 块请看这里stackoverflow.com/q/30991653/4413676
  • @HarveyFrench 我看到了 - 我不认为它是上述内容的特别可读的替代品......
  • 我评论说,您可以通过一些努力尝试在 vba 中捕获...认为您可能会在某个时候发现它有用...
  • @HarveyFrench 感谢您指出这一点。好的代码总是在健壮性、可读性和优雅之间取得平衡。我想,在你的后兜里有替代品总是好的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 2014-01-31
  • 1970-01-01
  • 2019-09-14
相关资源
最近更新 更多