在Excel VBA中创建自定义工作表函数 [英] Create a custom worksheet function in Excel VBA

查看:575
本文介绍了在Excel VBA中创建自定义工作表函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  = MyCustomFunction(A3)

可以这样吗?



编辑:



这是我的VBA功能签名:

 公共函数MyCustomFunction(str As String)As String 

该函数位于 ThisWorkbook 模块。如果我尝试在上面的工作表中使用它,我会得到 #NAME?错误。






解决方案(谢谢,codeape):当定义 ThisWorkbook 模块时,该函数不可访问。它必须在正确模块中,已经手动添加到工作簿中。

解决方案

是的可以。您只需在模块中定义VBA函数即可。请参阅 http://www.vertex42.com/ExcelArticles/user-defined-功能。



这是一个简单的例子:




  • 创建新工作簿

  • 切换到VBA视图(Alt-F11)

  • 插入模块:插入|模块

  • 模块内容:



 
Option Explicit

函数MyCustomFunction(输入)
MyCustomFunction = 42 +输入
结束函数




  • 切换回工作表(Alt-F11),然后输入一些值:



 
A1 :2
A2:= MyCustomFunction(A1)


I have a faint memory of being able to use VBA functions to calculate values in Excel, like this (as the cell formula):

=MyCustomFunction(A3)

Can this be done?

EDIT:

This is my VBA function signature:

Public Function MyCustomFunction(str As String) As String

The function sits in the ThisWorkbook module. If I try to use it in the worksheet as shown above, I get the #NAME? error.


Solution (Thanks, codeape): The function is not accessible when it is defined ThisWorkbook module. 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. See http://www.vertex42.com/ExcelArticles/user-defined-functions.html for a nice introduction with examples.

Here's a simple example:

  • Create a new workbook
  • Switch to VBA view (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:

A1: 2
A2: =MyCustomFunction(A1)

这篇关于在Excel VBA中创建自定义工作表函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆