【发布时间】:2016-07-21 12:39:28
【问题描述】:
这是一个以编程方式为 API 安装类型库的示例子程序。为什么错误处理例程会失败?我尝试遵循我在 Python 中熟悉的 try...except...finally 策略。
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
编辑
我从 main 中分出这一部分,因为 VBA 中的错误处理太荒谬了……对我来说更好的方法是使用布尔值实现 finite-state-machine。
回答
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
【问题讨论】:
-
VBA 中的错误处理不能像
try...catch那样工作——试图模仿它只会导致痛苦和痛苦。 Handle runtime errors the way they're supposed to be -
错误处理对我来说可能是最难的挑战。为了解决这个问题,我绘制了我的依赖项和子项的流程图/路线图,并创建了一组模块范围的布尔值,它们充当“门”中的“键”,其中门是 main 中的键相关调用。
-
编辑问题的答案会破坏 Stack Overflow 的问答性质。您可能应该发布答案。
-
@Mat'sMug,好的,我会的。谢谢。