如何在excel vba中调用ThisWorkbook中的模块

时间:2014-09-12 11:18:11

标签: excel vba excel-vba

我在Module1内部有一些模块,即 Module1有:

Sub Macro1
   ' Code
End Sub

Sub Macro2
   ' Code
End Sub

现在,我想在Microsoft Excel对象中提供的Module1中调用整个ThisWorkbook,即

内部ThisWorkbook

Sub CallingModule
     **Call Module1 (I want to call in this way)**
End Sub

但是,这不是正确的调用程序。请告诉我调用模块的正确程序。

1 个答案:

答案 0 :(得分:6)

与上面提到的Rory一样,您可以调用特定的例程,而不是整个模块。但是,如果您想从模块中调用所有例程 Macro1 Macro2 Macro3 等,那么可能吗?

请注意,如果您的Module1 SIMPLE ROUTINES 如下所示,则可以调用模块中的所有程序。

我们假设您在Module1

中有这些内容
Sub Sample1()
    MsgBox "I am Sample1"
End Sub

Sub Sample2()
    MsgBox "I am Sample2"
End Sub

Sub Sample3()
    MsgBox "I am Sample3"
End Sub

Sub Sample4()
    MsgBox "I am Sample4"
End Sub

enter image description here

现在只需将此代码粘贴到Module2即可。您还需要设置对Microsoft Visual Basic For Applications Extensibility xx.xx库的引用。

'~~> Code adapted from http://www.cpearson.com/excel/vbe.aspx
Sub CallModule1()
    Dim VBProj As VBIDE.VBProject
    Dim VBComp As VBIDE.VBComponent
    Dim CodeMod As VBIDE.CodeModule
    Dim LineNum As Long, NumLines As Long
    Dim ProcName As String
    Dim ProcKind As VBIDE.vbext_ProcKind
    Dim MyAr() As String
    Dim n As Long

    Set VBProj = ActiveWorkbook.VBProject
    Set VBComp = VBProj.VBComponents("Module1")
    Set CodeMod = VBComp.CodeModule

    With CodeMod
        LineNum = .CountOfDeclarationLines + 1
        Do Until LineNum >= .CountOfLines
        ReDim Preserve MyAr(n)
            ProcName = .ProcOfLine(LineNum, ProcKind)

            '~~> Store the routine names in an array
            MyAr(n) = ProcName
            n = n + 1

            LineNum = .ProcStartLine(ProcName, ProcKind) + _
                    .ProcCountLines(ProcName, ProcKind) + 1
        Loop
    End With

    '~~> This is where I am running every routine from Module1
    For n = LBound(MyAr) To UBound(MyAr)
        Run "Module1." & MyAr(n)
    Next n
End Sub

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

运行例程CallModule1()时,Module1中的每个过程都将自动运行。