Create a custom worksheet function in Excel VBA

后端 未结 2 879
时光说笑
时光说笑 2020-12-11 01:46

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)
相关标签:
2条回答
  • 2020-12-11 02:15

    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.

    Function MyCustomFunction(num As Variant)
        MyCustomFunction = 42 + num
    End Function
    
    0 讨论(0)
  • 2020-12-11 02:28

    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)
    
    0 讨论(0)
提交回复
热议问题