在通过早期绑定使用库之前,我可以使用晚期绑定来检查库的存在吗? [英] Can I use late binding to check the existence of a library before using it via early binding?

查看:102
本文介绍了在通过早期绑定使用库之前,我可以使用晚期绑定来检查库的存在吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢在VBA项目中使用早期绑定,因为我喜欢在开发过程中自动完成方法名称等.我也很高兴知道如果我拼写错误的方法名称,编译器会警告我.

I like to use early binding in my VBA projects, since I like the auto-complete of method names, etc. during development. I also like the confidence of knowing that the compiler will warn me if I've mis-spelled a method name.

但是,要使用早期绑定,我需要添加对相关库的引用(例如,"Microsoft Scripting Runtime").像这样的标准"库很好,但是有时我想使用用户计算机上可能存在或可能不存在的库.

However, to use early binding I need to add a reference to the relevant library (for example, the "Microsoft Scripting Runtime"). That's fine for "standard" libraries like that, but sometimes I want to use a library that may or may not be present on the user's machine.

理想情况下,如果库不存在,我想显示一条有用的消息(例如此计算机上未安装xyz,因此无法使用此功能").如果我只使用 late 绑定,那么我可以这样做:

Ideally, I'd like to display a useful message if the library is not present (such as "xyz is not installed on this computer, and so this feature cannot be used"). If I was using only late binding, then I could do this:

Dim o As Object
Set o = CreateObject("foo", "bar")

If o Is Nothing Then
    MsgBox "nope"
End If

但是,如果我添加了对该库的引用以使用早期绑定,则如果该库不存在,则在加载VBA项目时会出现编译错误.因此,代码的 none 都不运行(包括用于检测库不存在的代码).

But, if I've added a reference to the library in order to use early binding, then if the library is not present I get a compile error when my VBA project is loaded. Thus, none of the code runs (including the code to detect the non-existence of the library).

这个catch-22周围有什么办法吗?

Is there any way around this catch-22?

推荐答案

不是.

但是,我在开发中处理此问题的一种方法是拥有两个单独的声明行.根据我是从事开发工作还是发布到生产环境,我对此发表评论.您可以不理会其他所有内容(包括CreateObject行),然后只需要记住切换注释行并添加/删除引用本身即可.

However, one way I've dealt with this in development is to have two separate declaration lines. I comment one or the other depending on whether I am doing dev work or releasing to production. You can leave everything else alone (including the CreateObject line) and then you just need to remember to switch the commented line and add/remove the reference itself.

例如:

Dim o As foo.bar   'Comment out for production'
'Dim o As Object    ''Comment out for dev work'
Set o = CreateObject("foo", "bar")

If o Is Nothing Then
    MsgBox "nope"
End If

这篇关于在通过早期绑定使用库之前,我可以使用晚期绑定来检查库的存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆