在Excel VBA中创build一个自定义工作表函数
我有一个微弱的记忆,可以使用VBA函数来计算Excel中的值,就像这样(作为单元格公式):
=MyCustomFunction(A3)
可以这样做吗?
编辑:
这是我的VBA函数签名:
Public Function MyCustomFunction(str As String) As String
该函数位于ThisWorkbook
模块中。 如果我尝试在工作表中使用它,如上所示,我得到#NAME?
错误。
解决scheme(谢谢,codeape):定义ThisWorkbook
模块时,该function是不可访问的。 它必须位于“正确”模块中,该模块已手动添加到工作簿中。
是的,它可以。 您只需在模块中定义一个VBA函数。 请参阅http://www.vertex42.com/ExcelArticles/user-defined-functions.html以获得一个很好的介绍。
这是一个简单的例子:
- 创build一个新的工作簿
- 切换到VBA视图(Alt-F11)
- 插入一个模块:插入| 模
- 模块内容:
选项显式 函数MyCustomFunction(input) MyCustomFunction = 42 +input 结束function
- 切换回工作表(Alt-F11),并input一些值:
A1:2 A2:= MyCustomFunction(A1)
单词input需要被replace,因为它是一个基本的关键字。 试试数字。 你也可以进一步指定一个types,例如variant。
Function MyCustomFunction(num As Variant) MyCustomFunction = 42 + num End Function