You can use the following syntax to calculate the log (base 10) of a value using VBA:
Function FindLog(number) FindLog = Application.WorksheetFunction.Log(number) End Function
And you can use the following syntax to calculate the natural log of a value using VBA:
Function FindNaturalLog(number) FindNaturalLog = Log(number) End Function
The following examples show how to use each function in practice.
Example 1: Calculate Log (Base 10) Using VBA
To calculate the log (base 10) of a value in Excel, we would use the LOG function as follows:
This tells us that the log of 5 is 0.69879.
To replicate this functionality in VBA, we can define the following function:
Function FindLog(number) FindLog = Application.WorksheetFunction.Log(number) End Function
We can then type this function into cell B2 to calculate the log of the value in cell B1:
This tells us that the log of 5 is 0.69879.
This matches the value calculated by the LOG function in Excel.
Example 2: Calculate Natural Log Using VBA
To calculate the natural log of a value in Excel, we would use the LN function as follows:
This tells us that the natural log of 5 is 1.609438.
To replicate this functionality in VBA, we can define the following function:
Function FindNaturalLog(number) FindNaturalLog = Log(number) End Function
We can then type this function into cell B2 to calculate the natural log of the value in cell B1:
This tells us that the log of 5 is 1.609438.
This matches the value calculated by the LN function in Excel.
Additional Resources
The following tutorials explain how to perform other common tasks in VBA:
VBA: How to Write AVERAGEIF and AVERAGEIFS Functions
VBA: How to Write SUMIF and SUMIFS Functions
VBA: How to Write COUNTIF and COUNTIFS Functions