【问题标题】:what is the VBA for the USING statementUSING 语句的 VBA 是什么
【发布时间】:2014-07-22 10:21:05
【问题描述】:

在 csharp 或 vb.net 中,我们使用 using 语句的原因是我们知道的:无需显式编写即可打开和自动关闭数据库。 我想在VBA做同样的事情

  1. 怎么办?
  2. 所有 VB.NET 语句/关键字/在 VBA 中都可用吗?
  3. 如何判断给定语句在 VBA 中是否已知?是否有所有 VBA 语句/关键字/运算符的库(词汇表)?

c#

  using(var db=new MyDbContext()){
   //do work here
  }

vb.net

    Using s = New MyDbContext()
     '--..do work here
    End Using

【问题讨论】:

    标签: ms-access vba using-statement using-directives


    【解决方案1】:

    正如您所暗示的,仅回答您的第一个问题,Using 只是在实现IDisposable 接口的对象实例上调用Dispose() 的语法糖。

    相当于

    Dim s as MyDbContext
    Try
       s = New MyDbContext()
       // ...
    Finally
       s.Dispose()
    End Try
    

    由于VBA 不支持Using 糖,并且没有结构化的Try..Catch 异常处理,您需要在控制对象生命周期的所有路径上显式调用Dispose() ( MyDbContext 在你的情况下)。在这种情况下,您不妨使用.Close()

    【讨论】:

    • 非常感谢@StuartLC!它回答了我的问题
    • 由于Dispose() 通常只会调用Close() 来获取大多数数据库资源,因此在Close()Dispose() 之间没有真正的选择
    • 你可以在 VBA 中模拟一个 TRY CATCH 块请看这里stackoverflow.com/q/30991653/4413676
    【解决方案2】:

    没有与Using 语句等效的 VBA。

    VBA developer documentation 提供示例,甚至提供 VBA 文档的可下载离线版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      • 2023-03-17
      • 2014-09-09
      • 2022-01-13
      • 2018-01-07
      相关资源
      最近更新 更多