VBA for Excel 2007 tutorial-function to sum values

Create function to sum values

In this example, you will learn to create your own function to sum numerical values. This function can be run in the Excel sheet much like you do with other predefined functions such as count, counta, contif, sum, sumif,ect.

To run this example VBA code, you will need to create a standard module and copy and paste the VBA code below to the block of the module(Module1).Then in the Excel sheet, you can call the function to perform its task.

VBA for Excel: vba code to create a user-defined function to sum values

VBA for Excel: calling user-defined function

VBA code for this example:

Public Function Totalize(ParamArray par() As Variant)
  Dim i As Integer
  Dim result As Variant
  result = 0
  For i = 0 To UBound(par)
    result = result + par(i)
  Totalize = result
End Function
Note: by using ParamArray, you can pass an array parameters to the function. 


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.