[英]How to call a method in thisWorkbook from a module in Excel VBA?
[英]How to call a module in ThisWorkbook in excel vba
我在模塊內部的Module1中有一些宏,即Module1具有:
Sub Macro1
' Code
End Sub
Sub Macro2
' Code
End Sub
現在,我想在Microsoft Excel對象中的ThisWorkbook
調用整個Module1
,即
在本工作ThisWorkbook
:
Sub CallingModule
**Call Module1 (I want to call in this way)**
End Sub
但是,這不是正確的調用過程。 請告訴我正確的程序以調用模塊。
就像上面提到的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
現在,只需將此代碼粘貼到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中的每個過程將自動運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.