我有两个模块,Module1 和 Module2。
在模块 1 中:
Private Function myCheck() As Boolean
if [Operation] = [Something] then
myCheck = True
Else
myCheck = False
End if
End Sub
在模块2中,我想在模块1中运行myCheck sub,然后执行另一个操作:
Private Sub Execute()
[Operation 1]
If myCheck = True Then
[Operation 2]
Else
[Operation 3]
End If
End Sub
它不起作用。如果我将私有(private)函数 myCheck 放在同一模块中,那么它就可以工作。是否有特殊方法可以从另一个模块调用子函数或函数?
最佳答案
对模块 1 使用选项私有(private)模块,然后在模块 2 中使用:
对于子;限定您正在调用的模块及其所在的模块,如下所示:
Module1.myCheck()
对于私有(private)子站;使用 Application.Run 并用它所在的模块限定您正在调用的内容,如下所示:
Application.Run ("Module1.myCheck")
使用私有(private)模块会隐藏其包含在“开发人员”>“宏”列表中的子项目。
<小时/>进一步阅读:-)
仔细阅读下面代码中的注释,看看哪些有效,哪些无效。 要亲自确认这些行为: 创建一个新的Excel,打开Developer > Visual Basic,插入3个模块。 将以下代码块复制到相关模块中。
'In Module1
Option Explicit
Sub ScopeTrials()
'NOTES:
' Only NormalSubIn_NormalModule shows in Developer > Macros.
' As the default without a keyword is Public I have called
' these "Normal". I.e. you can use Public or Nothing wherever
' Normal is.
' A line commented out shows what doesn't work.
NormalSubIn_NormalModule
Call NormalSubIn_NormalModule
Application.Run ("NormalSubIn_NormalModule") 'Not recommended!
NormalSubIn_PrivateModule
Call NormalSubIn_PrivateModule
Application.Run ("NormalSubIn_PrivateModule") 'Not recommended!
'PrivateSubIn_NormalModule
'Call PrivateSubIn_NormalModule
'Module2.PrivateSubIn_NormalModule
'Call Module2.PrivateSubIn_NormalModule
Application.Run ("PrivateSubIn_NormalModule") 'Fails with duplicates! See Explanation
Application.Run ("Module2.PrivateSubIn_NormalModule")
'PrivateSubIn_PrivateModule
'Call PrivateSubIn_PrivateModule
'Module3.PrivateSubIn_PrivateModule
'Call Module3.PrivateSubIn_PrivateModule
Application.Run ("PrivateSubIn_PrivateModule") 'Fails with duplicates! See Explanation
Application.Run ("Module3.PrivateSubIn_PrivateModule")
'Explanation: if there is an identical sub in another Private Module, then this fails
'with Runtime Error 1004 (Macro not available or Macros Disabled), which is Misleading
'as the duplication and/or nonspecified module is the problem.
'I.e. always specify module!
'Also, this only fails when the line is actually run. I.e. Compile check doesn't find this
'when starting to Run the code.
End Sub
<小时/>
'In Module2
Option Explicit
Sub NormalSubIn_NormalModule() 'only THIS sub shows in Developer > Macros
MsgBox "NormalSubIn_NormalModule"
End Sub
Private Sub PrivateSubIn_NormalModule()
MsgBox "PrivateSubIn_NormalModule"
End Sub
<小时/>
'In Module3
Option Explicit
Option Private Module
Sub NormalSubIn_PrivateModule()
MsgBox "NormalSubIn_PrivateModule"
End Sub
Private Sub PrivateSubIn_PrivateModule()
MsgBox "PrivateSubIn_PrivateModule"
End Sub
关于vba - 从另一个模块调用私有(private)子模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50826976/