【发布时间】:2010-10-10 07:17:07
【问题描述】:
我的应用程序是为 VB.NET 中的扫描 MS Access 数据库构建的。
当 Access 应用程序分发给最终用户时,他们可能拥有不同版本的 COM 组件。是否可以以编程方式添加/删除引用以解决由于版本不同而导致的损坏引用?
请分享代码或链接以供参考。
【问题讨论】:
我的应用程序是为 VB.NET 中的扫描 MS Access 数据库构建的。
当 Access 应用程序分发给最终用户时,他们可能拥有不同版本的 COM 组件。是否可以以编程方式添加/删除引用以解决由于版本不同而导致的损坏引用?
请分享代码或链接以供参考。
【问题讨论】:
这里是一些示例代码:
从文件创建引用
Sub AddWS()
'Create a reference to Windows Script Host, '
'where you will find FileSystemObject '
'Reference name: "IWshRuntimeLibrary" '
'Reference Name in references list: "Windows Script Host Object Model" '
ReferenceFromFile "C:\WINDOWS\System32\wshom.ocx"
End Sub
Function ReferenceFromFile(strFileName As String) As Boolean
Dim ref As Reference
On Error GoTo Error_ReferenceFromFile
References.AddFromFile (strFileName)
ReferenceFromFile = True
Exit_ReferenceFromFile:
Exit Function
Error_ReferenceFromFile:
ReferenceFromFile = False
Resume Exit_ReferenceFromFile
End Function
删除参考
Sub DeleteRef(RefName)
Dim ref As Reference
'You need a reference to remove '
Set ref = References(RefName)
References.Remove ref
End Sub
You can use the references collection to find if a reference exists.
引用存在
Function RefExists(RefName)
Dim ref As Object
RefExists = False
For Each ref In References
If ref.Name = RefName Then
RefExists = True
End If
Next
End Function
发件人:http://wiki.lessthandot.com/index.php/Add,_Remove,_Check_References
【讨论】:
Dim ref As Reference 更改为 Dim ref As Object 以防止出现错误。
最好的解决方案是将 Access MDB 中的引用限制为内部 Access 组件。这将是 Access 引用、VBA 引用和 DAO 引用。所有其他外部库都应通过后期绑定使用。例如,如果您使用的是文件系统对象,而不是这个(参考 Windows 脚本宿主对象模型):
Dim objFSO As New FileSystemObject
If objFSO.FolderExists("\\d9m09521\WB\") Then
...
End If
您将删除引用并将其转换为:
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists("\\d9m09521\WB\") Then
...
End If
如果您担心每次使用 FSO 时都会对性能造成影响,您可以缓存对它的引用。我通常在函数中使用静态变量来返回这样的对象:
Public Function FSO() As Object
Static objFSO As Object
If objFSO Is Nothing Then
Set objFSO = CreateObject("Scripting.FileSystemObject")
End If
FSO = objFSO
End Function
现在,您可能想要花哨并能够拆除实例化的对象,在这种情况下,您可以执行以下操作:
Public Function FSO(Optional bolCloseObject As Boolean = False) As Object
Static objFSO As Object
If bolCloseObject Then
Set objFSO = Nothing
Exit Function
End If
If objFSO Is Nothing Then
Set objFSO = CreateObject("Scripting.FileSystemObject")
End If
FSO = objFSO
End Function
无论如何,关键在于后期绑定会在运行时解析外部库的位置,因此不会中断,除非外部库未安装或未正确注册。使用后期绑定,您可以捕获这两种情况,但使用早期绑定,您的整个 Access 应用程序就会中断。
【讨论】: