[英]Excel VBA On Error handling with User-Defined Type
this is an example sub to programatically install a type library for API. 这是一个示例子,可通过编程方式为API安装类型库。 Why is the error handling routine failing?
为什么错误处理例程失败? I attempted to follow the
try...except...finally
strategy I am familiar with from Python. 我试图遵循
try...except...finally
策略,这是我从Python熟悉的策略。
Sub CopyViewLayout():
'TRY:
On Error GoTo addReference
Dim App As femap.model
'COMPILE ERROR: USER TYPE NOT DEFINED
ResumeSub:
Dim App As femap.model
Set App = GetObject(, "femap.model")
Dim rc As Variant
Dim feView As femap.View
Set feView = App.feView
rc = feView.Get(0)
Exit Sub
'EXCEPT:
addReference:
Dim vbaEditor As VBIDE.VBE
Dim vbProj As VBIDE.VBProject
Dim checkRef As VBIDE.Reference
Dim filepath As String
Set vbaEditor = Application.VBE
Set vbProj = ActiveWorkbook.VBProject
filepath = "C:\apps\FEMAPv11\"
On Error GoTo Failure
vbProj.References.AddFromFile (filepath & "femap.tlb")
Set vbProj = Nothing
Set vbaEditor = Nothing
GoTo ResumeSub
'FINALLY
Failure:
MsgBox ("couldn't find type library, exiting sub")
End Sub
EDIT 编辑
I broke out this section from main because Error handling is just ridiculous in VBA... A better approach for me was to implement a finite-state-machine using Booleans. 我从主要部分中断了本节,因为错误处理在VBA中只是荒谬的。对我来说,更好的方法是使用布尔值实现有限状态机 。
answer 回答
Sub refcheck()
Dim i As Long
Dim FEMAP_GUID As String
FEMAP_GUID = "{08F336B3-E668-11D4-9441-001083FFF11C}"
With ActiveWorkbook.VBProject.references
For i = 1 To .Count
If .Item(i).GUID = FEMAP_GUID Then
Exit For
Else
'note: filepath is determined using Dir() elsewhere...
.AddFromFile (filepath & "femap.tlb")
Exit For
End If
Next
End With
End Sub
Error handling only handles runtime errors; 错误处理只能处理运行时错误。 not compile time errors.
不编译时间错误。 Use
采用
Dim App as Object
And make sure you only Dim App
once in your code. 并确保您的代码中仅
Dim App
一次。
By using As Object
, you can late bind any object to it. 通过使用
As Object
,您可以后期将任何对象绑定到该对象。 You lose Intellisense while youre coding thought. 您在编码时就失去了Intellisense。
Like Dick mentioned, use Late Binding but that alone is not enough. 就像Dick提到的那样,使用Late Binding,但仅此一项是不够的。 You will have to use it with proper Error Handling.
您必须将其与正确的错误处理一起使用。
For example 例如
Dim App As Object
On Error Resume Next
Set App = GetObject(, "femap.model")
On Error GoTo 0
If App Is Nothing Then
MsgBox "Please check if femap is installed"
Exit Sub
End If
'
'~~> Rest of the code
'
If you are sure that it is installed then you are getting the error because the relevant library is not referenced. 如果您确定已安装该库,则由于未引用相关库,因此会出现错误。 For that I would recommend having a look at How to add a reference programmatically
为此,我建议您看看如何以编程方式添加参考
I would however still suggest that you take the Late Binding route. 但是,我仍然建议您采用“后期绑定”路线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.