使用用户定义类型

时间:2016-04-01 16:02:44

标签: vba excel-vba excel

这是以编程方式为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中是荒谬的...对我来说更好的方法是使用布尔值来实现有限状态机

答案

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

2 个答案:

答案 0 :(得分:1)

错误处理仅处理运行时错误;不编译时间错误。使用

Dim App as Object

并确保您的代码只有Dim App一次。

通过使用As Object,您可以将任何对象延迟绑定到它。当你编码思想时,你会失去智能感知。

答案 1 :(得分:1)

就像迪克提到的那样,使用Late Binding,但仅凭这一点还不够。您必须使用正确的错误处理。

例如

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
'

如果您确定已安装它,那么您将收到错误,因为未引用相关库。为此,我建议您查看http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs

但我仍然建议您采用Late Binding路线。