我正在编写一个宏,其中包含对不同工作簿中的sub的调用。我可以使用原始工作簿中的代码运行其他工作簿中的sub。我正在尝试首先检查子/函数是否存在(如果sub已被重命名,则进行错误处理等。)
答案 0 :(得分:2)
您可以处理缺少的处理中的错误,也可以使用 Visual Basic for Applications可扩展性库
上有详细记录这是我在 Chip Peartsons网站上发现的代码并修改过:
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