Built-in Functions

Both Excel VBA and Python provide many built-in functions. Using built-in functions makes it easy to accomplish various tasks.

Common Built-in Functions

【Excel VBA】

Common built-in functions in Excel VBA mainly include mathematical functions, date/time functions, random number generation functions, data type conversion functions, and string manipulation functions, etc.

The mathematical functions provided by Excel VBA are shown in Table 10-1.

Table 10-1 Mathematical Functions in Excel VBA

Function Description
Abs Returns the absolute value
Exp Returns the power value with base e
Sqr Returns the square root (parameter ≥ 0)
Log Returns the natural logarithm (parameter > 0)

Continued Table

Function Description
Sgn Returns the sign of the parameter: 1 if > 0, 0 if = 0, -1 if < 0
Sin Returns the sine value
Cos Returns the cosine value
Tan Returns the tangent value
Atn Returns the arctangent value

The date/time functions provided by Excel VBA are shown in Table 10-2.

Table 10-2 Date/Time Functions in Excel VBA

Function Description
Date Returns the system date
Time Returns the system time
Year Returns the current year of the system
Month Returns the current month of the system
Day Returns the current day of the system
Weekday Returns the current weekday of the system
Hour Returns the hour of the system (0–23)
Minute Returns the minute of the system (0–59)
Second Returns the second of the system (0–59)

For string functions, please refer to Chapter 6. For data type conversion functions, please refer to Chapter 2.

In Excel VBA, the Rnd function can generate random numbers. To generate non-repeating random numbers, the Randomize function can be used to generate a random seed.

The following code tests some Excel VBA functions randomly. The sample file path is Samples\ch10\Excel VBA\BuiltInFunctions.xlsm.

code.vba
Sub Test()
    Const PI = 3.1415926

    ' Mathematical functions
    Debug.Print Exp(2)
    Debug.Print Sin(PI / 4)

    ' Date/time functions
    Debug.Print Date
    Debug.Print Year(Now)

    ' Random number generation function
    Randomize
    Debug.Print Rnd()
End Sub

Running the procedure outputs the calculation results of the test functions in the Immediate Window.

code.vba
7.38905609893065
0.707106771713121
2021/9/1
2021
0.1633657

【Python】

Built-in functions in Python include data type conversion functions, data manipulation functions, data input/output functions, file operation functions, and mathematical calculation functions, etc.

Data type conversion functions include bool, int, float, complex, str, list, tuple, dict, etc. They have been introduced when discussing variable data types, so they are not repeated here.

Data manipulation functions include type, format, range, slice, len, etc. Except for slice, all have been introduced. The slice function defines a slice object to specify the slicing method. Passing this slice object as a parameter to an iterable object enables slicing of that iterable object.

Below, we create a list; the first slice object takes the first 6 elements, and the second slice object takes every other element in the range 2–8. We then use these two slice objects to slice the list.

code.python
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> slice1 = slice(6)       # Take the first 6 elements
>>> a[slice1]
[0, 1, 2, 3, 4, 5]
>>> slice2 = slice(2, 9, 2)  # Take every other element in the range 2–8
>>> a[slice2]
[2, 4, 6, 8]

Data input/output functions include input and print, which were introduced in Chapter 1 and are not repeated here. File operation functions include file and open, used to open files.

Mathematical calculation functions are shown in Table 10-3.

Table 10-3 Mathematical Calculation Functions

Function Description Function Description
abs Returns the absolute value round Rounds a floating-point number
eval Evaluates a given expression sum Calculates the sum
max Returns the maximum value sorted Sorts
min Returns the minimum value filter Filters
pow Power operation

Several examples are given below to illustrate the use of mathematical calculation functions.

code.python
>>> abs(-3)                 # Absolute value
3
>>> pow(3, 2)               # Square of 3
9
>>> round(2.78)             # Round 2.78
3
>>> a = list(range(-5, 5))  # Create a list
>>> a
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
>>> max(a)                  # Maximum value of list elements
4
>>> min(a)                  # Minimum value of list elements
-5
>>> sum(a)                  # Sum of list elements
-5
>>> sorted(a, reverse=True) # Sort list elements in reverse order
[4, 3, 2, 1, 0, -1, -2, -3, -4, -5]
>>> def filtertest(a):      # Define a function: filter rule is element value > 0
... return a > 0
... 
>>> b = filter(filtertest, a) # Filter list a using the defined rule
>>> list(b)                 # Display filter result as a list
[1, 2, 3, 4]

Python Standard Module Functions

Python has many built-in standard modules, each containing many encapsulated functions to provide specific functionalities. Below, we mainly introduce the math, cmath, and random modules, which provide mathematical operations, complex number operations, and random number generation, respectively.

1. Mathematical Operation Functions in the math Module

The math module provides a large number of mathematical operation functions, including general mathematical operation functions, trigonometric functions, logarithmic functions, exponential functions, hyperbolic functions, number theory functions, and angle-radian conversion functions, etc.

Before using the mathematical operation functions in the math module, you need to import the math module first. The syntax for importing the math module is as follows:

code.python
>>> import math

The dir function can list all mathematical operation functions provided by the math module.

code.python
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

Mathematical operation functions in the math module are shown in Table 10-4.

Table 10-4 Mathematical Operation Functions in the math Module

Function Description Function Description
math.ceil(x) Returns the smallest integer greater than or equal to x math.sqrt(x) Returns the square root of x
math.fabs(x) Returns the absolute value of x math.sin(x) Returns the sine value of x
math.floor(x) Returns the largest integer less than or equal to x math.cos(x) Returns the cosine value of x
math.fsum(iter) Returns the sum of elements in an iterable object math.tan(x) Returns the tangent value of x
math.gcd(*ints) Returns the greatest common divisor of given integer arguments math.atan(x) Returns the arctangent value of x
math.isfinite(x) Returns True if x is not infinity or NaN, otherwise False math.asin(x) Returns the arcsine value of x
math.isinf(x) Returns True if x is infinity, otherwise False math.acos(x) Returns the arccosine value of x
math.isnan(x) Returns True if x is NaN, otherwise False math.sinh(x) Returns the hyperbolic sine value of x
math.isqrt(n) Returns the integer square root of n (square root rounded down), n ≥ 0 math.cosh(x) Returns the hyperbolic cosine value of x
math.lcm(*ints) Returns the least common multiple of given integer arguments math.tanh(x) Returns the hyperbolic tangent value of x
math.trunc(x) Returns the truncated integer of x math.asinh(x) Returns the inverse hyperbolic sine value of x
math.exp(x) Returns e raised to the power of x math.acosh(x) Returns the inverse hyperbolic cosine value of x
math.log(x[, base]) Returns the natural logarithm of x math.atanh(x) Returns the inverse hyperbolic tangent value of x
math.log2(x) Returns the base-2 logarithm of x math.dist(p, q) Returns the distance between points p and q
math.log10(x) Returns the base-10 logarithm of x math.degrees(x) Converts x from radians to degrees
math.pow(x, y) Returns x raised to the power of y math.radians(x) Converts x from degrees to radians

2. Complex Number Operation Functions in the cmath Module

Functions provided by the cmath module can be used for complex number operations. After importing the cmath module, the dir function can list all functions in the module.

code.python
>>> import cmath
>>> dir(cmath)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']

Most meanings of complex number operations are the same as those of real number operations, except that the parameters are complex numbers.

3. Random Number Generation Functions in the random Module

The random module provides various random number generation functions. The syntax for importing the random module is as follows:

code.python
>>> import random as rd

Use the random method to generate a random number between 0 and 1.

code.python
>>> rd01 = rd.random()
>>> print(rd01)
0.8929443975828429

Use the randrange method to randomly select a number from a specified sequence. The randrange method can specify the start, end, and step of the sequence. Below, we specify the sequence as 10–50 with a step of 2 and randomly select a number from this sequence.

code.python
>>> print(rd.randrange(10, 50, 2))
26

A loop can be used to continuously generate random numbers. Below, we continuously generate 10 random numbers from this sequence and form a list.

code.python
>>> lst = []
>>> for i in range(10):
... lst.append(rd.randrange(10, 50, 2))
... 
>>> lst
[14, 12, 46, 36, 40, 34, 18, 46, 22, 30]

The uniform method can generate a uniformly distributed random number within a specified range. Below, we generate 10 uniformly distributed random numbers between 1 and 2 and form a list.

code.python
>>> lst = []
>>> for i in range(10):
... a = rd.uniform(1, 2)
... lst.append(float("%0.3f" % a))
... 
>>> lst
[1.59, 1.974, 1.589, 1.918, 1.904, 1.666, 1.418, 1.024, 1.429, 1.643]

The choice method can randomly select a number from a specified iterable object. Below, we create a list and use the choice method to randomly select a number from it.

code.python
>>> lst = [1, 2, 5, 6, 7, 8, 9, 10]
>>> print(rd.choice(lst))
9

The shuffle method can shuffle the data in an iterable object, i.e., randomly reorder it.

code.python
>>> rd.shuffle(lst)
>>> lst
[2, 7, 5, 1, 8, 6, 10, 9]

The sample method can randomly select a sample of a specified size from a specified sequence. Below, we randomly select 6 numbers from list lst to form a new sample.

code.python
>>> samp = rd.sample(lst, 6)
>>> samp
[6, 1, 5, 2, 8, 7]