Determine if Sub Exists

P

Paige

Is there a way to determine if a sub exists? I have code in an add-in that
calls a sub in the active workbook per the example below. How do I determine
if that sub exists in the activeworkbook or not, to avoid an error?

WBName = ActiveWorkbook.Name
Application.Run "'" & WBName & "'!RemoveSN"
 
R

RB Smissaert

Just add an error handler:

Sub test()

On Error GoTo ERROROUT

Application.Run "xxx"

Exit Sub

ERROROUT:
MsgBox Err.Description 'or do whatever is suitable

End Sub


RBS
 
H

Howard31

Hi,
Try the following:

If ProcExists("RemoveSN") Then Application.Run "'" & WBName & "'!RemoveSN"

Function ProcExists(ProcName As String) As Boolean
Dim i
On Error Resume Next
MsgBox
ThisWorkbook.VBProject.VBE.ActiveCodePane.CodeModule.ProcBodyLine(ProcName,
vbext_pk_Proc)

If Err.Number <> 0 Then
ProcExists = False
Else
ProcExists = True
End If
End Function
 
H

Howard31

Actually there is no use for a MsgBox instead use the i variable as follows:

If ProcExists("RemoveSN") Then Application.Run "'" & WBName & "'!RemoveSN"

Function ProcExists(ProcName As String) As Boolean
Dim i
On Error Resume Next
i =
ThisWorkbook.VBProject.VBE.ActiveCodePane.CodeModule.ProcBodyLine(ProcName,
vbext_pk_Proc)

If Err.Number <> 0 Then
ProcExists = False
Else
ProcExists = True
End If
End Function
 
P

Paige

Thanks, RB and Howard, for both great ideas!

Howard31 said:
Actually there is no use for a MsgBox instead use the i variable as follows:

If ProcExists("RemoveSN") Then Application.Run "'" & WBName & "'!RemoveSN"

Function ProcExists(ProcName As String) As Boolean
Dim i
On Error Resume Next
i =
ThisWorkbook.VBProject.VBE.ActiveCodePane.CodeModule.ProcBodyLine(ProcName,
vbext_pk_Proc)

If Err.Number <> 0 Then
ProcExists = False
Else
ProcExists = True
End If
End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top