AdamDynamic
AdamDynamic

Reputation: 791

Check if function/sub is present in another workbook

I am writing a macro that includes a call on a sub in a different workbook. I can get the sub in the other workbook to run using code in the original workbook. I'm trying to first check whether the sub/function exists (error handling in case the sub has been renamed etc.).

Upvotes: 0

Views: 6433

Answers (1)

Our Man in Bananas
Our Man in Bananas

Reputation: 5981

you can either handle an error from a missing procesure, or you can use Visual Basic for Applications Extensibility Library

This is well documented on Chip Pearson's website

here is the code I found on Chip Peartsons website ages ago and modified:

Option Explicit    

Function checkProcName(wBook As Workbook, sModuleName As String, sProcName As String) As Boolean
' ===========================================================================
' Found on http://www.cpearson.com at http://www.cpearson.com/excel/vbe.aspx
' then modified
'
' USAGE:
' to check if a procedure exists, call 'checkProcName' passing
' in the target workbook (which should be open), the Module,
' and the procedure name
'
' ===========================================================================
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule

Dim ProcName As String
Dim LineNum As Integer
Dim ProcKind As VBIDE.vbext_ProcKind

    checkProcName = False

    Set VBProj = wBook.VBProject
    Set VBComp = VBProj.VBComponents(sModuleName)
    Set CodeMod = VBComp.CodeModule

    With CodeMod
        LineNum = .CountOfDeclarationLines + 1
        Do Until LineNum >= .CountOfLines
            ProcName = .ProcOfLine(LineNum, ProcKind)
            If ProcName = sProcName Then
                checkProcName = True
                Exit Do
            End If
            Debug.Print ProcName
            LineNum = .ProcStartLine(ProcName, ProcKind) + .ProcCountLines(ProcName, ProcKind) + 1
        Loop
    End With


End Function

Function ProcKindString(ProcKind As VBIDE.vbext_ProcKind) As String
    Select Case ProcKind
        Case vbext_pk_Get
            ProcKindString = "Property Get"
        Case vbext_pk_Let
            ProcKindString = "Property Let"
        Case vbext_pk_Set
            ProcKindString = "Property Set"
        Case vbext_pk_Proc
            ProcKindString = "Sub Or Function"
        Case Else
            ProcKindString = "Unknown Type: " & CStr(ProcKind)
    End Select
End Function

Upvotes: 2

Related Questions