我有两个模块,Module1和Module2。
在Module1中:
Private Function myCheck() As Boolean
if [Operation] = [Something] then
myCheck = True
Else
myCheck = False
End if
End Sub
在Module2中,我想在模块1中运行myCheck子,然后执行另一个操作:
Private Sub Execute()
[Operation 1]
If myCheck = True Then
[Operation 2]
Else
[Operation 3]
End If
End Sub
它不起作用。如果我将Private Function myCheck放在同一模块中,那么它可以工作。是否有一种特殊方法可以从另一个模块调用子或函数?
答案 0 :(得分:4)
使用模块1的选项专用模块,然后在模块2中使用
表示 Sub ;用你所使用的模块来限定你正在调用的内容,如下所示:
Module1.myCheck()
用于私有 Sub;使用Application.Run并使用它所在的模块限定你正在调用的内容,如下所示:
Application.Run ("Module1.myCheck")
使用私有模块隐藏它在Developer>中包含的sub / s宏列表。
进一步阅读: - )
仔细阅读以下代码中的注释,了解哪些功能有效,哪些功能无效。 要自己确认行为: 创建一个新的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
答案 1 :(得分:2)
您可以使用Application.Run
执行此操作:
Application.Run "Module1.myCheck"
宏将保持"隐形"为用户显示宏对话框(Alt + F8),因为它仍然是私有的。
编辑#1
第二种选择是在Sub
中引入虚拟变量作为可选参数,如下所示:
Public Sub notVisible(Optional dummyVal As Byte)
MsgBox "Im not visible because I take a parameter, but I can be called normally."
End Sub
这也会在宏对话框(Alt + F8)中隐藏宏,但现在可以通常的方式调用它。