Excel VBA macros

VBA macros in Excel

 Excel macros

Download the best tutorial, website and reference tool on Excel

Lesson 6: VBA for Excel Code for Functions

Three topics in this lesson: using Excel functions within macros, creating new Excel functions with VBA for Excel and then using VBA functions within macros.

Existing Excel Functions

There are hundreds of functions available in VBA. Most of the functions that you find in Excel are available through macros in this form:
Range("C1").Value= Application.WorksheetFunction.Sum(Range("A1:A32"))
this sentence sums the values of cell A1 to A32 and stores the total in cell C1.

New Excel Functions

You can create new functions in Excel. For example the function created by the code below will simply multiply the value of a cell by 2.

Function fctDouble(varInput)
  fctDouble = varInput * 2
End Function

Once this code is in a module in your workbook you access the new function the same way that you access the other functions by clicking on the icon function on the tool bar or from the menu bar "Insert/Functions". In the dialog box select the "User Defined" category and select "fctDouble" and follow the instructions.

VBA Functions

Here are some VBA functions that I use within my Excel macros:

LCase, UCase
The IF statements, the SELECT CASE and DO WHILE are all case sensitive.
When you test a string of characters and you don't know if the user will enter upper case or lower case letters, use the LCase or USase functions within your test and write the string in proper case:
If LCase(Selection.Value)= "toto" then...
or
Select Case LCase(Selection.Value)
or
Do While LCase(Selection.Value)<>"toto"

If UCase(Selection.Value)= "TOTO" then...
or
Select Case UCase(Selection.Value)
or
DO WHILE UCase(Selection.Value)<>"TOTO"

NOW()
NOW() is an Excel function but also a VBA function. With the following code the Excel formula NOW() is inserted in cell A1. The cell "A1" will show the date of the day and this date will change every time the workbook is opened:
Range("A1").Formula = "=Now()"

With the following code, the cell "A1" will carry the date when the procedure is executed and will keep this value until you execute the procedure again. It won't change every time you open the workbook.
Range("A1").Value = Now()

Download the best tutorial, website and reference tool on Excel

 Excel VBA macros

VBA macros in Excel

 Excel macros

All rights reserved PLI Consultant Inc.