The Average Function in VBA

104 2

    VBA

    • Visual Basic for Applications was Microsoft's first attempt to allow its MS Office software to have scripting built in. These scripts came in the form of macros that you would run from within different programs -- including Word, Access and Excel -- to perform repetitive tasks. However, Microsoft has phased out VBA in favor of the .Net Framework, a virtual machine to handle all programming and scripting in new Windows software.

    Average Function

    • The average function is a mathematical formula that allows you to determine the exact mean of a series of numbers. Visual Basic 6.0, the code that VBA is based on, did not have an average function built in, but most modern languages do. Whether done via a computer or by hand, the formula is exactly the same: You take a group of numbers, add them together and then divide by the number of numbers. For instance, say you have a series of numbers: 3, 4 and 5. Add these numbers together and divide by the quantity of numbers in the series, or 3. The average of this series of numbers is 4.

    How to Use Average in VBA

    • VBA does not have an average function. Create one by passing an array of numbers and its length, then have the function return the sum divided by the length. For example, you would input the following code into VBA:

      Function average(ListOfNumbers() as double, length as integer)

      dim a as integer

      for counter = 0 to (Length - 1)

      a = a + ListOfNumbers(counter)

      next

      Average = a / Length

      End Sub

      To find the average in a series of three numbers (3, 4 and 5), type the following line of code into VBA:

      dim array (3) as double

      array (0) = 3

      array (1) = 4

      array (2) = 5

      X = Average(array, length)

      Save and then run your VBA macro within MS software.

    Scripting/Macros

    • On a final note, when you enter text commands into a program to tell the program what to do, you are scripting or creating macros. It is almost like programming, and some scripting languages have evolved into programming languages in their own right. For example, you could convert all European styles of numbering in an Excel document from "1.000.000,00" (with periods) to display "$1,000,000.00," the American format using commas. Users create a simple script/macro using VBA to find all these values, convert them and then replace them. Plus, users can save the macro for future use.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.