The below example will help you to know how to call a function in Excel VBA Macros (it can be Excel VBA function, or user defined function). We generally create lot of function and we use the functions whenever and any time we want. The below example will help you to understand calling a simple function with and without parameters.
Calling a function Excel VBA
Here is the simple example to call the Now function to display the time. We use the Now function to get the System Current Time and Date.
'vba code to call a function Sub vba_code_to_call_a_function() MsgBox Now() End Sub
Calling a function Excel VBA: Function with Parameters
Here is the another example to call the Left function to extract the left part of a string. We use the left function to extract the left part of any string.
'vba code to call a function Sub vba_code_to_call_a_function_a() MsgBox Left("123", 2) End Sub
Calling a user defined Function Excel VBA
It is same as above, but we have to make sure that the functions is written before calling the function. Other wise it will though the run time error.
'User Defined Function Function mySum(ByVal A As Integer, ByVal B As Integer) mySum = A + B End Function 'vba code to call a the user defined function Sub vba_code_to_call_a_function_b() 'Calling udf MsgBox mySum(1, 5) End Sub
VBA code to Convert and Save the Excel to CSV – Instructions
Please follow the below step by step instructions to test this Example VBA Macro codes:
- Step 1: Open a New Excel workbook
- Step 2: Press Alt+F11 – This will open the VBA Editor (alternatively, you can open it from Developer Tab in Excel Ribbon)
- Step 3: Insert a code module from then insert menu of the VBE
- Step 4: Copy the above code and paste in the code module which have inserted in the above step
- Step 5: Now press F8 to debug the Macro to check how the VBA is calling the function while execution