Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Power Query Text.Insert Function Guide and Examples

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The Text.Insert function in Power Query is used to insert a specific string of text into another string at a designated character position. Unlike concatenation, which typically adds text to the beginning or end of a value, Text.Insert allows you to inject characters anywhere within the existing text string based on a zero-based index. This is particularly useful for fixing formatting errors, adding delimiters, or inserting prefixes into the middle of identification codes.

What You'll Need

  • Microsoft Excel or Power BI Desktop with Power Query installed.
  • A dataset containing a text column that requires modification.
  • Basic familiarity with the Power Query Editor interface and the "Add Custom Column" feature.

Step-by-Step

  1. Open Power Query Editor: In Excel, go to the Data tab and select Get Data > Launch Power Query Editor. In Power BI, click Transform Data from the Home ribbon.
  2. Identify the Target Column: Locate the column containing the text you wish to modify. Ensure the data type is set to "Text." If the column is currently set to a number or date, right-click the column header, select Change Type, and choose Text. The Text.Insert function will return an error if applied to non-text data types.
  3. Create a Custom Column: Navigate to the Add Column tab on the top ribbon and select Custom Column. This opens the Custom Column dialog box where you will write the M code formula.
  4. Enter the Column Name: In the New column name field, give your new column a descriptive name, such as "Formatted ID" or "Updated Text."
  5. Write the Text.Insert Formula: In the Custom column formula box, enter the function using the following syntax: Text.Insert([ColumnName], position, "inserted text").
    • Replace [ColumnName] by double-clicking the desired column from the Available columns list on the right.
    • Replace position with the integer representing where the insertion should start. Remember that Power Query uses zero-based indexing (the first character is 0).
    • Replace "inserted text" with the actual characters you want to add, enclosed in double quotation marks.
  6. Example Scenario: If you have a column named [ProductCode] with the value "ABC12345" and you want to insert a hyphen after the third character to make it "ABC-12345", your formula would be: Text.Insert([ProductCode], 3, "-").
  7. Validate the Result: Click OK. Power Query will generate a new column. Scroll through the rows to ensure the text was inserted at the correct position across different lengths of strings.
  8. Clean Up: If the original column is no longer needed, right-click the original column header and select Remove. You can then right-click the new custom column and select Rename to give it the original column's name.

Common Mistakes

One of the most frequent errors is forgetting that Power Query uses a zero-based index. Users often assume that the first character is position 1. If you want to insert a character at the very beginning of a string, you must use 0. If you use 1, the first character of the original string will remain at the start, and your inserted text will appear second.

Another common mistake is attempting to use Text.Insert on a column that contains null values. In Power Query, any operation performed on a null value typically results in a null output. If your dataset has empty cells, the function will not crash, but the result for those specific rows will be null, which might be unexpected if you were hoping to insert text into an empty field.

Case sensitivity is also a factor when combining Text.Insert with other functions. While Text.Insert itself doesn't care about the case of the text it is inserting, the M language is case-sensitive. Writing text.insert instead of Text.Insert (with a capital T and I) will result in a "Token Literal expected" or "The name 'text.insert' wasn't recognized" error.

Finally, users often forget the double quotes around the text being inserted. Because the third argument of the function must be a text string, failing to wrap the characters in quotes will cause Power Query to look for a column or a variable with that name, leading to an error stating that the identifier could not be found.

Tips

To make your insertions dynamic, you can replace the static position number with another function. For example, if you want to insert a character always before the last three digits of a string regardless of the total length, you can use Text.Length([ColumnName]) - 3 as the position argument. This ensures the insertion point shifts based on the length of the individual row's data.

If you need to insert text based on a condition, wrap the Text.Insert function inside an if...then...else statement. For instance, you could check if a string already contains a hyphen before inserting one: if Text.Contains([ColumnName], "-") then [ColumnName] else Text.Insert([ColumnName], 3, "-"). This prevents the creation of double hyphens in your data.

When dealing with very large datasets, creating a custom column is the standard approach, but you can also modify the existing column by editing the M code in the formula bar using Table.TransformColumns. This is more advanced but prevents the need to create and then delete a duplicate column, which can slightly improve performance and keep the Applied Steps list cleaner.

For those needing to insert multiple pieces of text at different positions, you can nest Text.Insert functions. The innermost function executes first, and the outer functions act upon that result. For example, Text.Insert(Text.Insert([Col], 2, "-"), 5, "-") would insert hyphens at both the 2nd and 5th positions.

Troubleshooting

If you encounter an "Expression.Error: We cannot convert the value #"123" to type Text," it means the column you are referencing is formatted as a number. To fix this, go to the step immediately preceding your custom column, click the data type icon (e.g., 1.2 or 123) next to the column header, and select Text. Once the data type is converted, the Text.Insert function will be able to process the values.

If the text is being inserted in the wrong place, double-check your index count. Count the characters starting from 0. If you want the insertion to happen after the 5th character, the position should be 5. If you want it to happen before the 5th character, the position should be 4. Testing with a single, short string in a temporary custom column is the fastest way to verify the index.

If the result of your custom column is entirely null, check your source data for nulls. You can handle this by using a null-coalescing operator or an if statement. For example, use Text.Insert(if [ColumnName] = null then "" else [ColumnName], 0, "Prefix"). This replaces nulls with an empty string before the insertion occurs, ensuring that the prefix is added even to previously empty cells.

If you receive a syntax error, check for missing commas or parentheses. The Text.Insert function requires exactly three arguments: the original text, the position, and the text to insert. Ensure there is a comma separating each of these three elements and that the entire expression is enclosed in a single set of parentheses.

Frequently Asked Questions

Can Text.Insert be used to replace text?

No, Text.Insert only adds text; it does not remove any existing characters. To replace text, you should use the Text.Replace function or Text.ReplaceRange.

Does the position argument support negative numbers?

No, the position must be a non-negative integer. If you provide a negative number, Power Query will return an error. To insert relative to the end of the string, subtract the desired offset from Text.Length([Column]).

Is there a limit to how many characters I can insert?

There is no specific character limit for the inserted string, other than the general memory limits of your system and the maximum string length supported by Power Query/M.

Can I insert a value from another column instead of a fixed string?

Yes. Instead of putting text in quotes (like "-"), you can simply reference another column name in brackets, such as Text.Insert([Column1], 2, [Column2]).

Will Text.Insert change the original data source?

No, Power Query is a transformation layer. It creates a set of instructions (Applied Steps) that are run when the data is loaded. Your original CSV, Excel file, or Database remains unchanged.