我对VBA的了解很少并且正在努力学习它。我制作了一个 VBA 脚本,如下所示:
Function doIt()
Dim c As int...
.............
.............
.............
c = callFunction
...............
..............
End Function
Function callFunction(byVal num As Int)
..........
..........
..........
End Function
如您所见,callFunction 是一个从主函数 doIt 调用的函数。假设 callFunction 计算一个整数的平方。整个 VBA 脚本保存在 C 盘相应 AddIns 文件夹下的 addIn 模块中。从 Excel 工作表调用时,函数 doIt 运行良好。但问题是,如果我从工作表调用函数 callFunction,它也可以工作。如何将 callFunction 限制为仅适用于 addIn 模块,以便只有模块可以使用它,并且如果有人从工作表中调用 callFunction(2) ,它不会在工作表中给出 2 的平方?
注意:即使我将其设为私有(private)
,仍然可以从工作表中调用它。
最佳答案
我认为您无法阻止允许在 VBA 和 Excel 单元格中访问它的函数功能。
但是,我有一些解决方法的想法,它允许您创建在单元格中调用时给出不同结果的函数,例如可以返回一些信息(或标准错误)而不是计算结果。
这是展示此功能的代码。我认为它非常清晰易懂,因此您不需要额外的评论。
Function callFunction(ByVal num As Integer)
On Error Resume Next
Dim tmpAdd
tmpAdd = Application.ThisCell.Address
If Err.Number = 0 Then
If Left(Application.ThisCell.Formula, 13) = "=callFunction" Then
'called from excel cell, but this function is called!
'returns any type of standard function error
callFunction = CVErr(XlCVError.xlErrNull)
Exit Function
End If
End If
'called from VBA/IDE environment or from other function
'standard calculation
callFunction = num ^ num
End Function
编辑 受到@DanielDusek 答案(但有点不完整)的启发,我将 Daniel 和我的解决方案混合在一起。因此,新的且相当完整的代码:
Function callFunction(ByVal num As Integer)
If TypeName(Application.Caller) = "Range" Then
If Left(Application.ThisCell.Formula, 13) = "=callFunction" Then
'called from excel cell, but this function is called!
'returns any type of standard function error
callFunction = CVErr(XlCVError.xlErrNull)
Exit Function
End If
End If
'called from VBA/IDE environment or from other function
'standard calculation
callFunction = num ^ num
End Function
如果在任何 VBA 函数/子例程中使用,无论调用位置如何(间接使用),这两种解决方案都会给出 num ^ num
结果。在Excel单元格中调用时会给出Error
值(直接使用)。
关于excel - 如何仅在模块上限制 VBA 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16431876/