在 Excel VBA 中创建自定义工作表函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/755812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a custom worksheet function in Excel VBA
提问by Tomalak
I have a faint memory of being able to use VBA functions to calculate values in Excel, like this (as the cell formula):
我对能够使用 VBA 函数在 Excel 中计算值的记忆很模糊,就像这样(作为单元格公式):
=MyCustomFunction(A3)
Can this be done?
这能做到吗?
EDIT:
编辑:
This is my VBA function signature:
这是我的 VBA 函数签名:
Public Function MyCustomFunction(str As String) As String
The function sits in the ThisWorkbookmodule. If I try to use it in the worksheet as shown above, I get the #NAME?error.
该函数位于ThisWorkbook模块中。如果我尝试在工作表中使用它,如上所示,我会收到#NAME?错误消息。
Solution (Thanks, codeape): The function is not accessible when it is defined ThisWorkbookmodule. It must be in a "proper" module, one that has been added manually to the workbook.
解决方案(谢谢,codeape):定义ThisWorkbook模块时无法访问该函数。它必须在“正确”的模块中,该模块已手动添加到工作簿中。
回答by codeape
Yes it can. You simply define a VBA function in a module. See http://www.vertex42.com/ExcelArticles/user-defined-functions.htmlfor a nice introduction with examples.
是的,它可以。您只需在模块中定义一个 VBA 函数。请参阅http://www.vertex42.com/ExcelArticles/user-defined-functions.html以获取带有示例的精彩介绍。
Here's a simple example:
这是一个简单的例子:
- Create a new workbook
- Switch to VBA view (Alt-F11)
- Insert a module: Insert | Module
- Module contents:
- 创建新工作簿
- 切换到 VBA 视图 (Alt-F11)
- 插入模块:插入 | 模块
- 模块内容:
Option Explicit
Function MyCustomFunction(input)
MyCustomFunction = 42 + input
End Function
- Switch back to worksheet (Alt-F11), and enter some values:
- 切换回工作表 (Alt-F11),然后输入一些值:
A1: 2 A2: =MyCustomFunction(A1)
回答by TMD
The word input needs to be replaced as it is a basic keyword. Try num instead. You can also go further by specifying a type, eg variant.
输入词需要替换,因为它是一个基本关键字。试试 num 。您还可以通过指定类型来更进一步,例如变体。
Function MyCustomFunction(num As Variant)
MyCustomFunction = 42 + num
End Function

