简体   繁体   English

在Excel VBA中创建自定义工作表函数

[英]Create a custom worksheet function in Excel VBA

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 ThisWorkbook module. 该函数位于ThisWorkbook模块中。 If I try to use it in the worksheet as shown above, I get the #NAME? 如果我尝试在工作表中使用它,如上所示,我得到#NAME? error. 错误。


Solution (Thanks, codeape): The function is not accessible when it is defined ThisWorkbook module. 解决方案(谢谢,代码):定义ThisWorkbook模块时无法访问该功能。 It must be in a "proper" module, one that has been added manually to the workbook. 它必须位于“正确”模块中,该模块已手动添加到工作簿中。

Yes it can. 是的,它可以。 You simply define a VBA function in a module. 您只需在模块中定义VBA函数。 See http://www.vertex42.com/ExcelArticles/user-defined-functions.html for a nice introduction with examples. 有关示例的详细介绍,请参阅http://www.vertex42.com/ExcelArticles/user-defined-functions.html

Here's a simple example: 这是一个简单的例子:

  • Create a new workbook 创建一个新的工作簿
  • Switch to VBA view (Alt-F11) 切换到VBA视图(Alt-F11)
  • Insert a module: Insert | 插入模块:插入| Module
  • Module contents: 单元内容:
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)

The word input needs to be replaced as it is a basic keyword. 输入一词需要替换,因为它是一个基本关键字。 Try num instead. 请尝试使用num。 You can also go further by specifying a type, eg variant. 您还可以通过指定类型(例如变体)来进一步发展。

Function MyCustomFunction(num As Variant)
    MyCustomFunction = 42 + num
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM