This repo contains custom functions I've developed throughout my experience as a programmer.
- Power Query (M Code)
Binary.UnzipDateTime.ToUnixTimeList.CorrelationList.RankList.InterceptList.OutliersList.SlopeList.PopulationStdDevList.VarianceList.WeightedAverageNumber.FromRomanNumber.IsIntegerNumber.IsPrimeNumber.ToRomanStatistical.NormDistStatistical.NormInvTable.AddListAsColumnTable.FixColumnNamesTable.PreprocessTextColumnsTable.RemoveBlankColumnsTable.TransposeCorrectlyText.CountCharText.ExtractNumbersText.HtmlToPlainText.pqText.RegexExtractText.RegexReplaceText.RegexSplitText.RegexTestText.RemoveAccentsText.RemoveDoubleSpacesText.RemoveLettersText.RemoveNumeralsText.RemovePunctuationsText.RemoveStopwordsText.RemoveWeirdChars
- VBA
AreArraysEqualsAutoFillFormulasCleanStringDisableRefreshAllEnableRefreshAllFileExistsFileNameIsValidGetAllFileNamesGetLettersOnlyGetMonthNumberFromNameGetStringBetweenGetStringWithSubstringInArrayGetTableColumnNamesIsAllTrueIsInArrayListObjectExistsPreviousMonthNumberRangeHasAnyFormulaRangeHasConstantValuesRangeIsHiddenRangeToHtmlSendEmailSetQueryFormulaStringContainsStringEndsWithStringStartsWithSubstringIsInArraySummationTableHasQueryWorksheetHasListObject
Extracts files from a ZIP archive and returns a table of entries with file names and decompressed content.
Binary.Unzip(ZIPFile as binary) as tableZIPFile— A binary containing a ZIP archive (for example, the result ofFile.Contents).
A table with the following columns:
FileName(text) — The entry name inside the ZIP.Content(binary or null) — The decompressed file content;nullif decompression failed or entry unsupported.
let
Source = Binary.Unzip(File.Contents("C:\Temp\archive.zip"))
in
SourceThis yields a table you can expand or transform. To read the content of the first file as text:
let
Files = Binary.Unzip(File.Contents("C:\Temp\archive.zip")),
FirstBinary = Files{0}[Content],
FirstText = if FirstBinary <> null then Text.FromBinary(FirstBinary) else null
in
FirstText- Author: Ignacio Barrau
- Source: ExtractZIP.pq
Converts a Power Query datetime value to Unix time (seconds since 1970-01-01 00:00:00).
DateTime.ToUnixTime(datetimeToConvert as datetime) as numberdatetimeToConvert: A datetime value to convert.
Converts datetime to Unixtime, which consists of a number representing the total seconds between datetimeToConvert and the Unix epoch (1970-01-01 00:00:00). Values are negative for datetimes before the epoch.
- No timezone conversion is performed — treat the input as UTC if you need UTC-based Unix time.
DateTime.ToUnixTime(#datetime(2023, 1, 1, 0, 0, 0)) // -> returns 1672531200Calculates the correlation coefficient between two lists of numeric values. Supports Pearson (linear) and Spearman (rank-based) correlation.
List.Correlation(
list1 as list,
list2 as list,
optional typeCorrelation as text
) as numberlist1: list of numeric values (nulls and non-numeric values are treated as 0).list2: list of numeric values (nulls and non-numeric values are treated as 0).typeCorrelation(optional): "Pearson" (default) or "Spearman". Case-insensitive.
A number representing the correlation coefficient:
- Pearson: standard Pearson correlation (linear relationship).
- Spearman: Spearman rank correlation (uses dense ranking; tied values receive the same rank).
- Input lists must be the same length; otherwise, an error is raised.
- Null, empty string, or non-numeric entries are converted to 0 before calculation.
- Result is returned as a decimal number (can be negative, positive, or
NaNif degenerate).
List.Correlation({0, 1, 3, 4}, {4, 5, 10, 30})
// -> 0.858575902776297 (Pearson, default)
List.Correlation({0, 1, 3, 4}, {4, 5, 10, 30}, "Spearman")
// -> 1 (Spearman: monotonic/rank-perfect relationship)
List.Correlation({0, null, 3, "a", 4}, {4, 5, null, 10, 30})
// -> 0.556720639738652 (non-numeric values are treated as 0)Returns a list of ranks for a given list of values. Tied values receive the same rank (dense ranking). The Result list preserves the input order.
List.Rank(
values as list,
optional order as Order.Type
) as listvalues: A list of values to rank. Values must be comparable (numbers, texts, dates, etc.).order(optional): UseOrder.AscendingorOrder.Descending. If omitted, the function treats the ordering as descending (i.e., highest value gets rank 1).
A list of integers with the same length as values, where each element is the rank (1-based) of the corresponding input value.
- Ranks are "dense": equal values receive the same rank and the next distinct value's rank increases by 1.
- Example (descending default): values {3,1,2,3} → ranks {1,3,2,1}
- The function returns ranks in the original input order.
- Comparison uses Power Query's Value.Compare, so mixed-type comparisons follow Power Query rules.
List.Rank({10, 10, 5, 7}) // {1, 1, 3, 2} (default: descending)
List.Rank({31, 11, 27, 31}, Order.Ascending) // {3, 1, 2, 3}
List.Rank({10, 10, 30, 30, 2}) // {2, 2, 1, 1, 3}Calculates the intercept of the linear regression line between two numerical lists X and Y.
List.Intercept(
X as list,
Y as list
) as numberX: A list of numerical values representing the independent variable.Y: A list of numerical values representing the dependent variable.
Returns a number representing the intercept of the linear regression line calculated using the least squares method. If the lists have different lengths, the function returns null.
- Both input lists must have the same length; otherwise, the function returns
null. - The function uses the least squares method to calculate the intercept.
- Non-numeric values in the lists will cause an error during calculation.
List.Intercept({1, 2, 3}, {4, 5, 6})
// -> -1 (example intercept value)
List.Intercept({1, 2}, {3})
// -> null (different lengths)Identifies outliers in a list of numerical values using the Interquartile Range (IQR) method.
List.Outliers(
values as list,
optional multiplier as number
) as listvalues: A list of numerical values to analyze for outliers.multiplier(optional): A number to adjust the IQR threshold for defining outliers. Default is 1.5.
Returns a list of outlier values identified in the input list based on the IQR method. If no outliers are found, the function returns an empty list.
- The function first removes nulls, empty strings, and whitespace entries, then selects only valid numeric values.
- Outliers are defined as values below Q₁ - 1.5×IQR or above Q₃ + 1.5×IQR, where Q₁ and Q₃ are the first and third quartiles respectively.
List.Outliers({1, 2, 3, 4, 100})
// -> {100} (100 is an outlier)
List.Outliers({10, 12, 14, 15, 16, 18, 20})
// -> {} (no outliers)
List.Outliers({1, 2, 3, 4, 50, 100}, 2)
// -> {100} (100 is an outlier with a higher multiplier)Calculates the slope of the linear regression between two numerical lists X and Y.
List.Slope(
X as list,
Y as list
) as nullable numberX: A list of numerical values representing the independent variable.Y: A list of numerical values representing the dependent variable.
Returns a number representing the slope of the linear regression line calculated using the least squares method. If the lists have different lengths, the function returns null.
- Both input lists must have the same length; otherwise, the function returns
null. - The function uses the least squares method to calculate the slope.
- Non-numeric values in the lists will cause an error during calculation.
List.Slope({1, 2, 3}, {4, 5, 6})
// -> 1 (example slope value)
List.Slope({1, 2}, {3})
// -> null (different lengths)Calculates the population standard deviation of a list of numerical values.
List.PopulationStdDev(values as list) as nullable numbervalues: A list of numerical values to calculate the population standard deviation.
Returns a number representing the population standard deviation of the input list. If the list is empty or contains no numeric values, the function returns null.
- The function calculates the population standard deviation using the formula:
$\sigma = \sqrt{\frac{1}{N} \sum_{i=1}^{N} (x_i - \mu)^2}$ -
$N$ is the number of values -
$x_i$ are the individual values -
$\mu$ is the mean of the values
-
- Non-numeric values, nulls, and empty strings are ignored in the calculation.
List.PopulationStdDev({2, 4, 4, 4, 5, 5, 7, 9})
// -> 2.8284271247461903 (example population standard deviation value)
List.PopulationStdDev({})
// -> null (empty list)Calculates the population variance of a list of numerical values.
List.Variance(values as list) as nullable numbervalues: A list of numerical values to calculate the population variance.
Returns a number representing the population variance of the input list. If the list is empty or contains no numeric values, the function returns null.
- The function calculates the population variance using the formula:
$\sigma^2 = \frac{1}{N} \sum_{i=1}^{N} (x_i - \mu)^2$ -
$N$ is the number of values -
$x_i$ are the individual values -
$\mu$ is the mean of the values
-
- Non-numeric values, nulls, and empty strings are ignored in the calculation.
List.Variance({1, 2, 3, 4, 5})
// -> 2.5 (sample variance value)
List.Variance({1, 2, 3, 4, 5}, true)
// -> 2 (population variance value)
List.Variance({})
// -> null (empty list)Calculates the weighted average of a list of values given a corresponding list of weights.
List.WeightedAverage(values as list, weights as list) as nullable numbervalues: A list of numerical values to calculate the weighted average.weights: A list of numerical weights corresponding to each value.
Returns a number representing the weighted average of the input values. If the lists have different lengths or if the sum of weights is zero, the function returns null.
- The function calculates the weighted average using the formula:
$WeightedAverage = \frac{\sum (x_i \times w_i)}{\sum w_i}$ -
$x_i$ are the individual values -
$w_i$ are the corresponding weights
-
List.WeightedAverage({1, 2, 3}, {4, 5, 6})
// -> 2.3333333333333335 (example weighted average value)Converts a Roman numeral (text) to a number.
Number.FromRoman(romanText as text) as numberromanText: A text string representing a Roman numeral.
Returns a number corresponding to the Roman numeral. If the input contains invalid characters, an error is raised.
- Supports standard Roman numeral characters: I, V, X, L, C, D, M (case-insensitive).
Number.FromRoman("XII") // -> 12
Number.FromRoman("invalid") // -> ErrorChecks if a given number is an integer.
Number.IsInteger(value as number) as logicalvalue: A number to check.
Returns true if the number is an integer, false otherwise.
Number.IsInteger(10) // -> true
Number.IsInteger(10.5) // -> falseChecks if a given number is a prime number.
Number.IsPrime(value as number) as logicalvalue: A number to check.
Returns true if the number is prime, false otherwise.
Number.IsPrime(7) // -> true
Number.IsPrime(10) // -> false- Author: Abigail
- Source: Abigail's regex to test for prime numbers
- YouTube Video: How on Earth does ^.?$|^(..+?)\1+$ produce primes?
Converts an integer number to a Roman numeral (between 1 and 3999).
Number.ToRoman(numberToConvert as number) as textnumberToConvert: The integer number to be converted to a Roman numeral.
Returns a text string representing the Roman numeral equivalent of the input integer. If the input number is outside the range of 1 to 3999, an error is raised.
Number.ToRoman(12) // -> "XII"
Number.ToRoman(0) // -> ErrorCalculates the value of the normal distribution (also known as Gaussian distribution) for a given input x. It supports both the probability density function (PDF) and the cumulative distribution function (CDF), depending on the cumulative parameter.
Statistical.NormDist(
x as number,
optional mean as number,
optional std as number,
optional accumulative as logical
) as number-
x: The value for which the normal distribution will be evaluated. -
mean(optional): The mean ($\mu$ ) of the distribution. Defaults to 0 if not provided. -
standard deviation(optional): The standard deviation ($\sigma$ ) of the distribution. Defaults to 1 if not provided. -
cumulative(optional): Logical value indicating whether to return the cumulative distribution (true) or the probability density (false). Defaults to true.
- When
cumulative = false, the function returns the probability density at point x using the formula:$\varphi(z)=\frac{1}{\sqrt{2 \pi}} \exp(-\frac{z^2}{2})$ - where
$z = \frac{x - \mu}{\sigma}$
- When
cumulative = true, the function returns the cumulative probability up to point$x$ using the formula:-
$\phi(z) = \frac{1}{2} + \frac{1}{\sqrt{\pi}} \int_{0}^{z / \sqrt{2}}{e^{-t^{2}}dt}$ . - where
$z = \frac{x - \mu}{\sigma}$
-
- The integral part is calculated by Gaussian Quadrature, which uses a 24-point Legendre-Gauss approximation for high accuracy.
- $ \frac{1}{\sqrt{\pi}} \int_{0}^{z / \sqrt{2}}{e^{-t^{2}}dt} = \sqrt{\frac{2}{\pi}} \cdot \frac{z}{4} \cdot \sum_{i=1}^{24}{w_{i} \cdot \exp(-\frac{z^{2}(t_{i}+1)^2}{8})}$
- where
$w_{i}$ and$t_{i}$ are parameters provided by a Gaussian Quadrature table for 24-point approximation
- This function is useful for statistical modeling, hypothesis testing, and data normalization.
Returns the normal cumulative probability up to a given cumulative = false, returns the normal probability density at point cumulative is false.
Example 1: Calculating the cumulative probability for a value of
Statistical.NormDist(100, 80, 10)Result
0.97724986805182079Example 2: Calculating the normal PDF for given mean and standard deviation.
Statistical.NormDist(100, 80, 10, false)Result
0.0539909665131881Example 3: In order to calculate the standard normal CDF, just don't input any mean nor standard deviation.
Statistical.NormDist(1.96)Result
0.97500210485177974Example 4: Calculating the standard normal PDF.
Statistical.NormDist(1.96, null, null, false)Result
0.058440944333451476- Gaussian Quadrature Weights and Abscissae
- Author: Mike "Pomax" Kamermans
- Published at: June 5th, 2011
Returns the inverse of the cumulative distribution function (CDF) of the normal distribution.
Statistical.NormInv(
probability as number,
optional mean as number,
optional sd as number
) as number-
probability: A probability value between 0 and 1. Values outside this range are clamped to 0 or 1. -
mean(optional): The mean ($\mu$ ) of the distribution. Defaults to 0 if not provided. -
standard deviation(optional): The standard deviation ($\sigma$ ) of the distribution. Defaults to 1 if not provided.
A number representing the value probability. If neither mean nor standard deviation are specified, returns the value probability.
- The function uses a rational approximation algorithm to compute the inverse of the standard normal distribution.
- The input probability is clamped between 0 and 1. Values outside this range are adjusted to the nearest valid bound.
- For
probability = 0, the result is negative infinity (Number.NegativeInfinity). - For
probability = 1, the result is positive infinity (Number.PositiveInfinity).
Example 1: Returns
Statistical.NormInv(0.9, 100, 15)Result
119.22327346210234Example 2: If neither mean nor standard deviation are informed, returns the value
Statistical.NormInv(0.9)Result
1.2815515641401563- An algorithm for computing the inverse normal cumulative distribution function
- Author: Peter John Acklam
- Original Site: http://home.online.no/~pjacklam/notes/invnorm
- Published at: May 4th, 2003
Adds a new column to a table using values from a provided list. The new column can be inserted at a specified position and can have a defined data type.
Table.AddListAsColumn(
tbl as table,
columnName as text,
columnValues as list,
optional position as number,
optional columnType as type
) as tabletbl: The input table to which the new column will be added.columnName: The name of the new column to be added.columnValues: A list of values to populate the new column.position(optional): The position (0-based index) where the new column should be inserted. If not specified, the column is added at the end.columnType(optional): The data type of the new column. If not specified, the column will have typeany.
Returns a new table with the added column populated with values from the provided list. If the list has fewer items than the number of rows in the table, nulls are added for the remaining rows. If the list has more items than the number of rows, extra items are ignored.
- If the
positionparameter is provided, the new column will be inserted at the specified index. If the index is out of bounds, an error will occur. - If the
columnTypeparameter is provided, the new column will be created with the specified data type. If not provided, the column will have typeany.
Example 1: Add a list as a new column at the end of the table.",
let
Source = Table.FromRecords({[A=1, B=2], [A=3, B=4]}),
NewColumnValues = {10, 20},
Result = Table.AddListAsColumn(Source, "C", NewColumnValues)
in
ResultResult
| A | B | C |
|---|---|---|
| 1 | 2 | 10 |
| 3 | 4 | 20 |
Example 2: Add a list as a new column at a specific position with a defined data type.
let
Source = Table.FromRecords({[A=1, B=2], [A=3, B=4]}),
NewColumnValues = {10, 20},
Result = Table.AddListAsColumn(Source, "C", NewColumnValues, 2, Int64.Type)
in
ResultResult
| A | C | B |
|---|---|---|
| 1 | 10 | 2 |
| 3 | 20 | 4 |
Example 3: If list has fewer items than rows, nulls are added for remaining rows.
let
Source = Table.FromRecords({[A=1, B=2], [A=3, B=4], [A=5, B=6]}),
NewColumnValues = {10, 20},
Result = Table.AddListAsColumn(Source, "C", NewColumnValues)
in
ResultResult
| A | B | C |
|---|---|---|
| 1 | 2 | 10 |
| 3 | 4 | 20 |
| 5 | 6 | null |
Example 4: If list has more items than rows, extra items are ignored.
let
Source = Table.FromRecords({[A=1, B=2], [A=3, B=4]}),
NewColumnValues = {10, 20, 30, 40},
Result = Table.AddListAsColumn(Source, "C", NewColumnValues)
in
ResultResult
| A | B | C |
|---|---|---|
| 1 | 2 | 10 |
| 3 | 4 | 20 |
Cleans and standardizes column names in a table by removing unwanted characters, trimming spaces, and applying specified text formatting (Proper, Lower, Upper). It also removes columns with default names like 'Column1', 'Column2', etc.
Table.FixColumnNames(
tbl as table,
optional textFormat as text
) as tabletbl: The input table whose column names need to be fixed.textFormat(optional): The desired text format for the column names. Accepts 'Proper', 'Lower', or 'Upper'. If not specified, no formatting is applied.
A table with cleaned and standardized column names.
- The function processes the column names of the provided table to ensure they are clean and standardized. It removes non-printable characters, trims leading and trailing spaces, replaces non-breaking spaces with regular spaces, eliminates duplicated spaces, and applies the specified text formatting (Proper, Lower, Upper). Additionally, it removes any columns that have default names such as 'Column1', 'Column2', etc., ensuring that only relevant columns remain in the Result table.
- If the
textFormatparameter is not provided, the function will only clean the column names without applying any specific text formatting.
Table.FixColumnNames(SourceTable, "Proper") // Cleans and formats column names to Proper case.
Table.FixColumnNames(SourceTable, "Lower") // Cleans and formats column names to Lower case.
Table.FixColumnNames(SourceTable, "Upper") // Cleans and formats column names to Upper case.
Table.FixColumnNames(SourceTable) // Cleans column names without applying any specific text formatting.This function cleans and formats text columns in a table. It removes line breaks, non-standard spaces, duplicated spaces, and applies optional casing (Proper, Lower, or Upper). You can specify which columns to process or let the function automatically detect all text columns.
Table.PreprocessTextColumns(
tbl as table,
optional columnNames as list,
optional textCasing as text
) as tabletbl: The input table containing text columns to be cleaned and formatted.columnNames: (optional) A list of column names to be processed. If not provided or empty, all columns of type text or nullable text will be processed.textCasing: (optional) A string indicating the desired text casing format. Accepted values are:- "Proper": Capitalizes the first letter of each word.
- "Lower": Converts all texts to lowercase.
- "Upper": Converts all texts to uppercase.
- If not specified, casing is not changed.
- The function replaces line feed characters (
#(lf)) with spaces. - It removes non-breaking spaces (
Character.FromNumber(160)), trims leading/trailing spaces, and collapses multiple spaces into one. - This function is useful for preparing text data for analysis, comparison, or display.
Example 1: Clean all text columns
let
Source = #table({"Name", "Comment"}, {
{" JOHN DOE ", "Hello#(lf)World"},
{" jane smith", "Nice to meet you"}
}),
Result = Table.PreprocessTextColumns(Source)
in
ResultResult
| Name | Comment |
|---|---|
| JOHN DOE | Hello World |
| jane smith | Nice to meet you |
Example 2: Clean and apply Proper case to selected columns
let
Source = #table({"Name", "Note"}, {
{" MARIA clara", "great#(lf)job"},
{"joão SILVA", "excellent work"}
}),
Result = Table.PreprocessTextColumns(Source, {"Name", "Note"}, "Proper")
in
ResultResult
| Name | Note |
|---|---|
| Maria Clara | Great Job |
| João Silva | Excellent Work |
Removes columns from a table that contain only blank values.
Table.RemoveBlankColumns(tbl as table) as tabletbl: The table from which blank columns will be removed.
Transposing the table and changing the first column name
let
Source = #table({"A", "B"}, {{null, "value1"}, {"", "value2"}}),
Result = Table.RemoveBlankColumns(Source)
in
ResultResult
| B |
|---|
| value1 |
| value2 |
Transposes a table by converting selected columns (or all columns if none are specified) into rows, promotes headers, and adds a new column containing the original column names. This is useful for restructuring data while preserving column identity.
Table.TransposeCorrectly(
tbl as table,
optional columns as list,
optional firstColumnName as text
) as tabletbl: The input table whose columns will be transposed.columnNames: (optional) A list of column names to transpose. If not provided, all columns in the table will be transposed.firstColumnName: (optional) The name to assign to the first column of the transposed table. If not provided, the first name from the columns list will be used.
- The function promotes the first row of the transposed table as headers.
- A new column is added containing the original column names, inserted at the beginning of the table.
- This function is useful for reshaping data, especially when preparing it for pivoting or normalization.
Example 1: Transposing all columns
let
Source = #table({"A", "B", "C"}, {{1, 2, 3}, {4, 5, 6}}),
Result = Table.TransposeCorrectly(Source)
in
ResultResult
| A | 1 | 4 |
|---|---|---|
| B | 2 | 5 |
| C | 3 | 6 |
Example 2: Transposing only the selected columns
let
Source = #table({"A", "B", "C"}, {{1, 2, 3}, {4, 5, 6}}),
Result = Table.TransposeCorrectly(Source, {"A", "B"})
in
ResultResult
| A | 1 | 4 |
|---|---|---|
| B | 2 | 5 |
Example 3: Transposing the table and changing the first column name
let
Source = #table({"A", "B", "C"}, {{1, 2, 3}, {4, 5, 6}}),
Result = Table.TransposeCorrectly(Source, null, "D")
in
ResultResult
| D | 1 | 4 |
|---|---|---|
| B | 2 | 5 |
| C | 3 | 6 |
Counts the occurrences of a specific character in a given text string.
Text.CountChar(
textToCount as nullable text,
charToCount as text
) as numbertextToCount: The text string in which to count occurrences of the character.charToCount: The character to count within the text string.
Returns a number representing the count of occurrences of the specified character in the input text. If the input text is null, returns 0.
- The function is case-sensitive; 'a' and 'A' are considered different characters.
- If
charToCountis an empty string, the function returns 0.
Text.CountChar("hello world", "o") // -> 2
Text.CountChar(null, "a") // -> 0Extracts all numeric values from a given text string and returns them as a list of numbers.
Text.ExtractNumbers(inputText as text) as listinputText: The text string from which to extract numeric values.
Returns a list of numbers extracted from the input text. If no numbers are found, returns an empty list.
Example 1: Extracts numbers from a string containing mixed characters.
let
ExtractedNumbers = Text.ExtractNumbers("Order #12345: 67 items at $89 each.")
in
ExtractedNumbersResult
{12345, 67, 89}Example 2: Returns an empty list when no numbers are present.
let
ExtractedNumbers = Text.ExtractNumbers("No numbers here!")
in
ExtractedNumbersResult
{}Converts HTML content to plain text by stripping HTML tags.
Text.HtmlToPlainText(htmlText as text) as texthtmlText: The HTML text to be converted to plain text.
Returns the plain text content extracted from the HTML input.
Text.HtmlToPlainText("<p>Hello <b>World</b>!</p>") // -> "Hello World!"Extracts a substring from a text using a regular expression pattern.
Text.RegexExtract(
textToExtract as text,
regexPattern as text,
optional global as logical,
optional caseInsensitive as logical,
optional multiline as logical
) as anytextToExtract: The input text from which to extract the substring.regexPattern: The regular expression pattern to use for extraction.global(optional): A logical value indicating whether to extract all matches (true) or just the first match (false). Default isfalse.caseInsensitive(optional): A logical value indicating whether the regex matching should be case insensitive. Default isfalse.multiline(optional): A logical value indicating whether to treat the input text as multiline. Default isfalse.
Returns the extracted substring(s) based on the regex pattern. If global is true, returns a list of all matches; otherwise, returns the first match or null if no match is found.
- Uses .NET regular expressions for pattern matching.
- If
globalistrue, returns a list of all matches; otherwise, returns the first match ornullif no match is found. - Due to Power Query's JavaScript parser limitations, some advanced regex features like lookbehind '(?<=pattern)' and negative lookbehind '(?<!pattern)' and certain flags (
s,u,v,d,y) are not supported. - Only the flags
g,i,mare available.
Text.RegexExtract("Hello World", "W.*d") // -> "World"
Text.RegexExtract("abc 123 def 456", "\d+", true) // -> {"123", "456"}
Text.RegexExtract("Hello\nWorld", "^W.*d", false, false, true) // -> "World"Replaces substrings in a text that match a regular expression pattern with a specified replacement string.
Text.RegexReplace(
textToModify as text,
regexPattern as text,
replacer as text,
optional global as logical,
optional caseInsensitive as logical,
optional multiline as logical
) as nullable texttextToModify: The input text in which to perform the replacements.regexPattern: The regular expression pattern to match substrings for replacement.replacer: The string to replace matched substrings with.global(optional): A logical value indicating whether to replace all occurrences (true) or just the first occurrence (false). Default isfalse.caseInsensitive(optional): A logical value indicating whether the regex matching should be case insensitive. Default isfalse.multiline(optional): A logical value indicating whether to treat the input text as multiline. Default isfalse.
Returns the modified text with the specified replacements. If no matches are found, returns the original text.
- Uses .NET regular expressions for pattern matching and replacement.
- If
globalistrue, replaces all matches; otherwise, replaces only the first match. - Due to Power Query's JavaScript parser limitations, some advanced regex features like lookbehind '(?<=pattern)' and negative lookbehind '(?<!pattern)' and certain flags (
s,u,v,d,y) are not supported. - Only the flags
g,i,mare available.
Text.RegexReplace("Hello World", "World", "Universe") // -> "Hello Universe"
Text.RegexReplace("abc 123 def 456", "\d+", "number", true) // -> "abc number def number"
Text.RegexReplace("Hello\nWorld", "^W.*d", "Everyone", false, false, true) // -> "Hello\nEveryone"Splits a text into a list of substrings based on a regular expression pattern.
Text.RegexSplit(
textToSplit as text,
regexPattern as text,
optional caseInsensitive as logical,
optional multiline as logical
) as listtextToSplit: The input text to be split.regexPattern: The regular expression pattern to use as the delimiter for splitting.caseInsensitive(optional): A logical value indicating whether the regex matching should be case insensitive. Default isfalse.multiline(optional): A logical value indicating whether to treat the input text as multiline. Default isfalse.
Returns a list of substrings obtained by splitting the input text at each match of the regex pattern.
- Uses .NET regular expressions for pattern matching.
- Due to Power Query's JavaScript parser limitations, some advanced regex features like lookbehind '(?<=pattern)' and negative lookbehind '(?<!pattern)' and certain flags (
s,u,v,d,y) are not supported. - Only the flags
i,mare available.
Text.RegexSplit("apple,banana,cherry", ",") // -> {"apple", "banana", "cherry"}
Text.RegexSplit("one1two2three3", "\d") // -> {"one", "two", "three", ""}
Text.RegexSplit("Hello\nWorld", "\n", false, true) // -> {"Hello", "World"}Tests whether a text matches a regular expression pattern.
Text.RegexTest(
textToTest as text,
regexPattern as text,
optional caseInsensitive as logical,
optional multiline as logical
) as logicaltextToTest: The input text to be tested against the regex pattern.regexPattern: The regular expression pattern to test.caseInsensitive(optional): A logical value indicating whether the regex matching should be case insensitive. Default isfalse.multiline(optional): A logical value indicating whether to treat the input text as multiline. Default isfalse.
Returns true if the input text matches the regex pattern, false otherwise.
- Uses .NET regular expressions for pattern matching.
- Due to Power Query's JavaScript parser limitations, some advanced regex features like lookbehind '(?<=pattern)' and negative lookbehind '(?<!pattern)' and certain flags (
s,u,v,d,y) are not supported. - Only the flags
i,mare available.
Text.RegexTest("Hello World", "World") // -> true
Text.RegexTest("abc 123", "^\d+$") // -> false
Text.RegexTest("Hello\nWorld", "^W.*d", false, true) // -> trueRemoves accents from characters in a text string.
Text.RemoveAccents(inputText as text) as textinputText: The text string from which to remove accents.
Returns the input text with all accented characters replaced by their unaccented equivalents.
Text.RemoveAccents("Café") // -> "Cafe"
Text.RemoveAccents("naïve") // -> "naive"Removes consecutive double spaces from a text string, replacing them with single spaces.
Text.RemoveDoubleSpaces(inputText as text) as textinputText: The text string from which to remove double spaces.
Returns the input text with all consecutive double spaces replaced by single spaces.
Text.RemoveDoubleSpaces("This is a test.") // -> "This is a test."Removes all alphabetic characters from a text string, leaving only non-letter characters.
Text.RemoveLetters(textToModify as text) as texttextToModify: The text string from which to remove alphabetic characters.
Returns the input text with all alphabetic characters removed.
let
RemovedLetters = Text.RemoveLetters("Hello123 World!")
in
RemovedLetters // -> "123 !"Removes all numeric characters from a text string, with an option to also remove Roman numerals.
Text.RemoveNumerals(
textToRemove as text,
optional removeRomanNumerals as logical
) as texttextToRemove: The text string from which to remove numeric characters.removeRomanNumerals(optional): A logical value indicating whether to also remove Roman numeral characters (I, V, X, L, C, D, M). Default isfalse.
Returns the input text with all numeric characters (and optionally Roman numerals) removed.
Text.RemoveNumerals("Room 101 IV") // -> "Room IV"
Text.RemoveNumerals("Room 101 IV", true) // -> "Room "Removes all punctuation characters from a text string.
Text.RemovePunctuations(
textToRemove as nullable text,
optional replacer as text
) as texttextToRemove: The text string from which to remove punctuation characters.replacer(optional): A text string to replace punctuation characters with. If omitted, punctuation characters are removed without replacement.
Returns the input text with all punctuation characters removed or replaced by the specified replacer.
Text.RemovePunctuations("Hello, World!") // -> "Hello World"
Text.RemovePunctuations("Hello, World!", " ") // -> "Hello World "Removes common Portuguese stopwords from a text string to enhance text analysis.
Text.RemoveStopwords(
textToModify as nullable text,
optional undesirableWords as list
) as texttextToModify: The text string from which to remove stopwords.undesirableWords(optional): A list of additional words to remove from the text. Default is an empty list.
Returns the input text with all Portuguese stopwords and any additional specified words removed.
Text.RemoveStopwords("Este é um exemplo de texto para remover palavras comuns.")
// -> "exemplo texto remover palavras comuns."
Text.RemoveStopwords("Este é um exemplo de texto para remover palavras comuns.", {"exemplo", "texto"})
// -> "remover palavras comuns."Removes special and non-printable characters from a text string, with an option to replace them with spaces.
Text.RemoveWeirdChars(
textToClean as text,
optional replacer as text
) as texttextToClean: The text string to be cleaned.replacer(optional): A text string to replace special characters with. If omitted, special characters are replaced by an white space.
Returns the cleaned text with special characters either removed or replaced by the specified replacer.
Text.RemoveWeirdChars("Hello" & Character.FromNumber(0) & "World!") // -> "Hello World!"
Text.RemoveWeirdChars("Hello" & Character.FromNumber(0) & "World!", "_") // -> "Hello_World!"Compares two arrays to check if they are equal, meaning they have the same size and identical elements in the same order.
AreArraysEqual(
Array1 As Variant,
Array2 As Variant
) As BooleanArray1: First array to compareArray2: Second array to compare
Returns True if both arrays are equal, False otherwise.
- Arrays must have the same upper and lower bounds
- Arrays must have identical elements in the same positions
- The function performs an element-by-element comparison
- Returns
Falseif arrays have different sizes - Can compare arrays of any type since parameters are declared as Variant
Dim arr1 As Variant
Dim arr2 As Variant
arr1 = Array(1, 2, 3)
arr2 = Array(1, 2, 3)
If AreArraysEqual(arr1, arr2) Then
Debug.Print "Arrays are equal"
Else
Debug.Print "Arrays are different"
End IfAutomatically fills formulas across a range using a reference cell's formula. The reference cell can be either the first or last cell containing a formula in the range.
AutoFillFormulas(
rng As Range,
Optional UseLastCellAsRef As Boolean = False
)rng: The range where formulas will be filledUseLastCellAsRef: (optional) Boolean flag to determine which cell to use as referenceFalse(Default): Uses the first cell with formula as referenceTrue: Uses the last cell with formula as reference
- Does nothing if the range is empty (Nothing) or contains only one cell
- Only works if the range contains at least one formula
- Uses R1C1 formula notation to ensure proper relative references when filling
- Only fills formulas in cells that are part of the specified range
- Requires the helper function
RangeHasAnyFormulato check for formulas in the range
Dim rng As Range
Set rng = Range("A1:A10")
AutoFillFormulas rng 'Uses first formula cell as reference
'Or using the last cell as reference:
AutoFillFormulas rng, TrueCleans a string by removing or replacing special characters and control characters with spaces.
CleanString(
myString As String,
Optional ReplaceBySpace As Boolean = True,
Optional ConvertNonBreakingSpace As Boolean = True
) As StringmyString: The input string to be cleanedReplaceBySpace: (optional) Boolean flag that determines if special characters should be replaced by spacesTrue(Default): Replaces special characters with spacesFalse: Removes special characters without replacement
ConvertNonBreakingSpace: (optional) Boolean flag to handle non-breaking spacesTrue(Default): Converts non-breaking spaces (ASCII 160) to regular spacesFalse: Leaves non-breaking spaces unchanged
Returns the cleaned string with special characters either removed or replaced by spaces.
- Removes ASCII control characters (0-31)
- Handles special characters like ASCII 127, 129, 141, 143, 144, and 157
- Converts non-breaking spaces to regular spaces (when enabled)
- Trims leading and trailing spaces from the final result
- Preserves all other printable characters
Dim cleanedStr As String
' Replace special characters with spaces
cleanedStr = CleanString("Hello" & Chr(0) & "World")
Debug.Print cleanedStr ' Result: "Hello World"
' Remove special characters
cleanedStr = CleanString("Hello" & Chr(0) & "World", False)
Debug.Print cleanedStr ' Result: "HelloWorld"
' Keep non-breaking spaces
cleanedStr = CleanString("Hello" & Chr(160) & "World", True, False)
Debug.Print cleanedStr ' Result: Original string unchangedDisables the "Refresh All" functionality for OLEDB connections in a specified workbook.
DisableRefreshAll(ByRef wb As Workbook)wb: Reference to the workbook where OLEDB connections will be modified
- Improve performance by preventing unnecessary data refreshes
- Control which connections should be updated during a "Refresh All" operation
- Selectively manage data refresh behavior in workbooks with multiple connections
- Only affects OLEDB type connections
- Does not modify PowerPivot or other connection types
- Changes are applied to each connection individually
- The connections will still be refreshable individually, just not through "Refresh All" option
- Changes are made directly to the workbook passed as parameter
Dim wb As Workbook
Set wb = ThisWorkbook
DisableRefreshAll wbEnables the "Refresh All" functionality for OLEDB connections in a specified workbook.
EnableRefreshAll(ByRef wb As Workbook)wb: Reference to the workbook where OLEDB connections will be modified
- Restore default refresh behavior for OLEDB connections
- Enable batch updates of multiple connections
- Ensure all OLEDB connections are included in "Refresh All" operations
- Manage data refresh settings after temporary disablement
- Only affects OLEDB type connections
- Does not modify PowerPivot or other connection types
- Changes are applied to each connection individually
- Allows connections to be updated when using "Refresh All" command
- Changes are made directly to the workbook passed as parameter
Dim wb As Workbook
Set wb = ThisWorkbook
EnableRefreshAll wbChecks if a file exists at the specified file path.
FileExists(FilePath As String) As BooleanFilePath: The complete path to the file being checked
Returns True if the file exists, False otherwise.
- Uses VBA's
Dirfunction to test file existence - Works with any file type
- Path must be accessible from the current environment
- Case-insensitive file path checking
Dim exists As Boolean
exists = FileExists("C:\Documents\myfile.xlsx")
If exists Then
Debug.Print "File exists"
Else
Debug.Print "File not found"
End If- Original source: www.TheSpreadsheetGuru.com/The-Code-Vault
- Resource: http://www.rondebruin.nl/win/s9/win003.htm
Validates if a given string can be used as a valid file name by checking for illegal characters.
FileNameIsValid(FileName As String) As BooleanFileName: The string to be validated as a file name
Returns True if the file name is valid, False if it contains illegal characters or is empty.
- Checks for the following illegal characters:
\ / : * ? < > | [ ] " - Returns
Falsefor empty strings - Case-sensitive validation
- Does not check file name length restrictions
- Does not validate against reserved Windows file names
Dim isValid As Boolean
isValid = FileNameIsValid("my_file.txt")
Debug.Print isValid ' True
isValid = FileNameIsValid("file*.txt")
Debug.Print isValid ' False
isValid = FileNameIsValid("folder/file.txt")
Debug.Print isValid ' False- Author: Jon Peltier
- Source: www.TheSpreadsheetGuru.com/the-code-vault
Retrieves an array of all file names from a specified folder and its subfolders, with optional file extension filtering.
GetAllFileNames(
FolderPath As String,
Optional fileExt As String
) As String()FolderPath: The path to the folder to search infileExt: (optional) File extension to filter results. If omitted, returns all files
Returns a zero-based string array containing all matching file names.
- Recursively searches through all subfolders
- Case-insensitive file extension matching
- Uses
FileSystemObjectfor file system operations - Returns only file names, not full paths
- Extension filter doesn't require the dot prefix
- Empty array if no files are found
- Requires reference to Microsoft Scripting Runtime (or late binding)
Scripting.FileSystemObjectreference
Dim files() As String
Dim i As Long
' Get all Excel files
files = GetAllFiles("C:\Documents", "xlsx")
' Get all files regardless of extension
files = GetAllFiles("C:\Documents")
' Print all found files
For i = 0 To UBound(files)
Debug.Print files(i)
Next iExtracts only ASCII letters (a–z) from a string and returns them in lowercase.
GetLettersOnly(Text As String) As StringText: The input string to process.
Returns a string containing only the letters a–z (converted to lowercase). Returns an empty string if no ASCII letters are found.
- Filters characters using ASCII range 97–122 (letters a–z).
- Converts characters to lowercase before testing and Result.
- Does not preserve original letter case.
- Does not include accented letters, non-Latin characters, or other alphabetic Unicode letters.
- Useful for normalizing or sanitizing input to ASCII letters only.
Dim result As String
result = GetLettersOnly("Hello, World! 123")
Debug.Print result ' "helloworld"
result = GetLettersOnly("Ábç Def")
Debug.Print result ' "def" (accented letters removed)Converts a month name to its corresponding numeric value (1-12).
GetMonthNumberFromName(MonthName As String) As IntegerMonthName: The name of the month (full or abbreviated, in any language supported by Excel)
Returns an integer from 1 to 12 representing the month number.
- Works with month names in any language supported by Excel Accepts both full month names and abbreviated forms
- Case-insensitive
- Returns error if month name is invalid
Dim monthNum As Integer
monthNum = GetMonthNumberFromName("January")
Debug.Print monthNum ' Prints 1
monthNum = GetMonthNumberFromName("Jan")
Debug.Print monthNum ' Prints 1
monthNum = GetMonthNumberFromName("Janeiro")
Debug.Print monthNum ' Prints 1 (Portuguese)
monthNum = GetMonthNumberFromName("Janvier")
Debug.Print monthNum ' Returns 1 (French)Extracts a substring between two specified delimiter strings.
GetStringBetween(
str As String,
startStr As String,
endStr As String
) As Stringstr: The input string to search instartStr: The starting delimiter stringendStr: The ending delimiter string
Returns the text found between the start and end strings. Returns an empty string if no match is found.
- Uses VBScript RegExp for pattern matching
- Creates RegExp object using late binding to avoid explicit reference requirement
- Case-insensitive search
- Non-greedy matching (returns shortest match)
- Returns only the first match if multiple exist
- Removes the delimiter strings from the result
Dim result As String
result = GetStringBetween("Hello [World] Test", "[", "]")
Debug.Print result ' Returns "World"
result = GetStringBetween("<tag>Content</tag>", "<tag>", "</tag>")
Debug.Print result ' Returns "Content"
result = GetStringBetween("No delimiters here", "[", "]")
Debug.Print result ' Returns ""Searches through an array of strings and returns the first string that contains a specified substring.
GetStringWithSubstringInArray(
SubString As String,
SourceArray As Variant,
Optional CaseSensitive As Boolean = False
) As StringSubString: The text to search for within each array elementSourceArray: Array containing strings to search throughCaseSensitive: (optional) Boolean flag to enable case-sensitive search. Default is False
Returns the first string from the array containing the substring. Returns an empty string if no match is found.
- Only processes elements that are strings (type
vbString) - Ignores non-string elements in the array
- Case-insensitive by default
- Returns first match found and exits
- Works with arrays of any dimension
- Requires
StringContainsfunction
Dim testArray As Variant
Dim result As String
testArray = Array("Hello World", "Test String", "Another Text")
result = GetStringWithSubstringInArray("World", testArray)
Debug.Print result ' Returns "Hello World"
result = GetStringWithSubstringInArray("text", testArray)
Debug.Print result ' Returns "Another Text"
result = GetStringWithSubstringInArray("none", testArray)
Debug.Print result ' Returns ""Returns the header names of an Excel ListObject (table) as a zero-based string array.
GetTableColumnNames(lo As ListObject) As String()lo: The ListObject (Excel table) to read column headers from
Returns a zero-based array of strings containing the table column header values in left-to-right order.
- Includes hidden columns and preserves the table column order.
Dim colNames() As String
Dim i As Long
Set tbl = ThisWorkbook.Worksheets("Sheet1").ListObjects("Table1")
colNames = GetTableColumnNames(tbl)
For i = 0 To UBound(colNames)
Debug.Print colNames(i)
Next iChecks if all elements in a boolean array are True.
IsAllTrue(blnArray As Variant) As BooleanblnArray: Array containing boolean values to be checked
Returns True if all elements in the array are boolean True, otherwise returns False.
- Validating that multiple conditions are all met
- Checking status of multiple boolean flags
- Quality control checks where all criteria must be true
- Returns
Falseif any element is not a boolean type - Returns
Falseif any element isFalse - Early exit when first non-true value is found
- Can handle arrays of any dimension
- Array must be passed as
Varianttype
Dim testArray As Variant
testArray = Array(True, True, True)
Debug.Print IsAllTrue(testArray) ' Returns True
testArray = Array(True, False, True)
Debug.Print IsAllTrue(testArray) ' Returns False
testArray = Array(True, "True", True)
Debug.Print IsAllTrue(testArray) ' Returns False (non-boolean element)Checks whether a value exists in a one-dimensional array.
IsInArray( _
ValueToBeFound As Variant, _
SourceArray As Variant _
) As BooleanValueToBeFound: The value to search for (any Variant).SourceArray: The one-dimensional array to search (Variant).
Returns True if the value is found in the array, otherwise returns False.
- Expects a one-dimensional array; passing an uninitialized or multi-dimensional array may cause errors.
Dim arr As Variant
arr = Array("apple", "banana", "cherry")
If IsInArray("banana", arr) Then
Debug.Print "Found"
Else
Debug.Print "Not found"
End IfChecks whether a ListObject (Excel table) with a given name exists in a workbook.
ListObjectExists( _
ByRef wb As Workbook, _
loName As String _
) As Booleanwb: Workbook to search.loName: Name of the table (ListObject) to find.
Returns True if a ListObject with the specified name is found in any worksheet of the workbook; otherwise returns False.
- Performs a direct name comparison (behavior may be affected by the project's Option Compare setting).
Dim exists As Boolean
exists = ListObjectExists(ThisWorkbook, "Table1")
If exists Then
Debug.Print "Table exists"
Else
Debug.Print "Table not found"
End IfReturns the numeric month (1–12) that precedes the month of a given date.
PreviousMonthNumber(dt As Date) As Integerdt: Date value used to determine the previous month
Returns an Integer from 1 to 12 representing the previous month. For dates in January, returns 12 (December).
Dim prev As Integer
prev = PreviousMonthNumber(DateSerial(2025, 3, 15))
Debug.Print prev ' returns 2 (February)
prev = PreviousMonthNumber(DateSerial(2025, 1, 10))
Debug.Print prev ' returns 12 (December)Checks if a given range contains any cells with formulas.
RangeHasAnyFormula(ByVal rng As Range) As Booleanrng: The range to be checked for formulas
Returns True if the range contains at least one formula, False otherwise.
- Returns
Falseif the range is Nothing - Uses error handling to detect the presence of formulas
- Shows an error message if any unexpected error occurs during execution
- Uses Excel's
SpecialCellsmethod withxlCellTypeFormulasto perform the check
Dim rng As Range
Set rng = Range("A1:D10")
If RangeHasAnyFormula(rng) Then
Debug.Print "Range contains at least one formula"
Else
Debug.Print "Range contains no formulas"
End If- Displays a message box with error details if an unexpected error occurs
- Properly handles the "No cells were found" error which indicates no formulas are present
Checks whether a given range contains any constant (non-formula) cells.
RangeHasConstantValues(rng As Range) As Booleanrng: Range to check for constant values.
Returns True if the range contains at least one constant cell; otherwise returns False. If rng is Nothing the function returns False.
Dim rng As Range
Set rng = ThisWorkbook.Worksheets("Sheet1").Range("A1:A10")
If RangeHasConstantValues(rng) Then
Debug.Print "Range contains constants"
Else
Debug.Print "Range contains no constants or is invalid"
End IfDetermines whether a given range is entirely hidden (no visible cells).
RangeIsHidden(rng As Range) As Booleanrng: The Range to check for visibility.
Returns True if the range contains no visible cells (i.e., is hidden). Returns False if at least one cell in the range is visible or if rng is Nothing.
Dim rng As Range
Set rng = ThisWorkbook.Worksheets("Sheet1").Range("A1:A10")
If RangeIsHidden(rng) Then
Debug.Print "Range is hidden (no visible cells)."
Else
Debug.Print "Range has visible cells."
End IfConverts an Excel Range into an HTML string by copying the range to a temporary workbook, publishing that sheet as an HTML file, and returning the file contents.
RangeToHtml(rng As Range) As Stringrng: The Range to convert to HTML.
Returns a string containing the HTML representation of the provided range. Returns an empty string if an error occurs.
- Creates a temporary workbook, pastes the range (values and formats) and removes drawing objects before publishing.
- Uses the system temporary folder (Environ$("temp")) to create an intermediate .htm file.
- Reads the generated HTML file into memory and deletes the temporary file and workbook.
- Replaces
align=centerwithalign=leftin the resulting HTML. - Images/drawing objects are deleted in the temporary workbook to avoid embedding them in the HTML.
Dim html As String
html = RangeToHtml(ThisWorkbook.Worksheets("Sheet1").Range("A1:D10"))
' html now contains the HTML representation of the rangeSends an HTML email using CDO (Collaboration Data Objects) with NTLM authentication, typically used in corporate environments with Exchange Server.
SendEmail( _
Sender As String, _
Recipient As String, _
Subject As String, _
Message As String, _
Optional CarbonCopy As String, _
Optional BlindCarbonCopy As String _
)Sender: Email address of the senderRecipient: Email address(es) of the recipient(s)Subject: Subject line of the emailMessage: HTML-formatted body of the emailCarbonCopy: (optional) Email address(es) for CC recipientsBlindCarbonCopy: (optional) Email address(es) for BCC recipients
- Uses CDO with NTLM authentication (Windows Authentication)
- Configured for SMTP with STARTTLS (port 587)
- Supports HTML formatting in the message body
- Multiple recipients can be specified using semicolon (;) as separator
- No explicit error handling is implemented
CDO_DEFAULT_SETTINGS: -1 (Use system default settings)CDO_NTLM_AUTHENTICATION: 2 (Windows Authentication)CDO_SEND_USING_PORT: 2 (Direct SMTP)CDO_SERVER_PORT: 587 (STARTTLS port)CDO_SMTP_SERVER: "mailhost.yourdomain.net" (SMTP server address)
- Requires CDO to be available on the system
- Requires proper SMTP server configuration
- Requires appropriate network/firewall access
Call SendEmail( _
"sender@company.com", _
"recipient@company.com", _
"Test Subject", _
"<h1>Hello</h1><p>This is a test email.</p>", _
"cc@company.com", _
"bcc@company.com")Modifies a Power Query formula in the current workbook based on a given value, handling different data types appropriately.
SetQueryFormula( _
queryName As String, _
value As Variant _
)queryName: Name of the Power Query to modifyvalue: Value to set in the query formula (supportsString,Date, andByte Array)
- Requires Excel version that supports Power Query
' Set a string value
SetQueryFormula "MyQuery", "Hello ""World""" ' Results in: "Hello ""World"""
' Set a date value
SetQueryFormula "MyQuery", DateSerial(2023, 10, 17) ' Results in: #date(2023,10,17)
' Set a byte array
Dim byteArr() As Byte
byteArr = Array(1, 2, 3)
SetQueryFormula "MyQuery", byteArr ' Results in: {1,2,3}Checks if a string contains another string as a substring, with optional case sensitivity.
StringContains( _
str1 As String, _
str2 As String, _
Optional caseSensitive As Boolean = False _
) As Booleanstr1: The main string to search instr2: The substring to search forcaseSensitive: (optional) Boolean flag to enable case-sensitive search. Default isFalse
Returns True if str2 is found within str1, False otherwise.
- Text validation
- String searching
- Pattern matching without regular expressions
- Case-insensitive text comparisons
Dim result As Boolean
result = StringContains("Hello World", "world")
Debug.Print result ' Returns True
result = StringContains("Hello World", "WORLD")
Debug.Print result ' Returns True
result = StringContains("Hello World", "world", True)
Debug.Print result ' Returns False
result = StringContains("Test", "xyz")
Debug.Print result ' Returns FalseChecks if a string ends with another string, with optional case sensitivity.
StringEndsWith( _
str1 As String, _
str2 As String, _
Optional caseSensitive As Boolean = False _
) As Booleanstr1: The main string to checkstr2: The ending string to look forcaseSensitive: (optional) Boolean flag to enable case-sensitive comparison. Default isFalse
Returns True if str1 ends with str2, False otherwise. Also returns False if str2 is longer than str1.
- File extension validation
- Text suffix checking
- String pattern matching
- Domain name validation
Dim result As Boolean
result = StringEndsWith("Hello World", "world")
Debug.Print result ' Returns True
result = StringEndsWith("Hello World", "WORLD")
Debug.Print result ' Returns True
result = StringEndsWith("Hello World", "World", True)
Debug.Print result ' Returns True
result = StringEndsWith("Test", "xyz")
Debug.Print result ' Returns FalseChecks whether a string starts with a specified substring, with optional case sensitivity.
StringStartsWith( _
str1 As String, _
str2 As String, _
Optional caseSensitive As Boolean = False _
) As Booleanstr1: The main string to check.str2: The prefix substring to look for.caseSensitive: (optional) IfTrue, comparison is case-sensitive; ifFalse(default), comparison is case-insensitive.
Returns True if str1 starts with str2; otherwise returns False. Also returns False if str2 is longer than str1.
Dim result As Boolean
result = StringStartsWith("Report.xlsx", "Report")
Debug.Print result ' True
result = StringStartsWith("Report.xlsx", "report")
Debug.Print result ' True (case-insensitive)
result = StringStartsWith("Report.xlsx", "report", True)
Debug.Print result ' False (case-sensitive)
result = StringStartsWith("Test", "LongPrefix")
Debug.Print result ' FalseSearches a one-dimensional array for any string element that contains a specified substring and returns True on the first match.
StringStartsWith( _
str1 As String, _
str2 As String, _
Optional caseSensitive As Boolean = False _
) As BooleansubStr: The substring to search for.srcArray: One-dimensional array containing elements to search.caseSensitive: (optional) IfTrue, performs a case-sensitive search; default isFalse.
Returns True if any string element in srcArray contains subStr; otherwise returns False.
- Only inspects elements typed as
String; non-string elements are ignored.
- Depends on the helper function
StringContainsfor substring checks.
Dim arr As Variant
arr = Array("Hello World", "Sample", "Test")
Debug.Print SubstringIsInArray("world", arr) ' True (case-insensitive)
Debug.Print SubstringIsInArray("WORLD", arr, True) ' False (case-sensitive)Computes the numeric summation of a mathematical expression over an integer index range.
Summation( _
Expression As String, _
First As Long, _
Last As Long _
) As DoubleExpression: A string representing the math expression in terms of a variable (e.g."2*n-1"or"1/x^2"). The function extracts the variable name as the last alphabetical character found in the expression.First: Starting integer index.Last: Ending integer index.
Returns the summation's result from expression evaluated for the index running from First to Last.
- The variable used in Expression is determined by extracting letters from the expression and taking the last letter. Ensure your expression contains the intended variable and that it is the last letter in the expression if multiple letters appear
- Depends on the helper function
GetLettersOnlyin order to identify the variable in expression
Debug.Print Summation("2*n-1", 1, 10) ' prints 100
Debug.Print Summation("1/x^2", 1, 1000000) ' ≈ 1.64 (approaches π²/6)
Debug.Print Summation("n^2", 1, 5) ' prints 55Checks whether a ListObject (Excel table) has an associated QueryTable.
TableHasQuery(tbl As ListObject) As Booleantbl: The ListObject (table) to check.
Returns True if the table has an associated QueryTable; otherwise returns False. If tbl is Nothing, the function returns False.
Dim tbl As ListObject
Dim hasQuery As Boolean
Set tbl = ThisWorkbook.Worksheets("Sheet1").ListObjects("Table1")
hasQuery = TableHasQuery(tbl)
If hasQuery Then
Debug.Print "Table has a QueryTable"
Else
Debug.Print "Table does not have a QueryTable"
End IfChecks whether a worksheet contains at least one ListObject (table).
WorksheetHasListObject(ws As Worksheet) As Booleanws: Worksheet to check for ListObjects.
Returns True if the worksheet contains one or more ListObjects; otherwise returns False.
Dim hasTable As Boolean
hasTable = WorksheetHasListObject(ThisWorkbook.Worksheets("Sheet1"))
If hasTable Then
Debug.Print "Sheet1 contains at least one table."
Else
Debug.Print "Sheet1 contains no tables."
End If