Power Query Text.Middle: Extract Substrings Guide
In this article
The Power Query Text.Middle function extracts a specific number of characters from the middle of a text string, starting at a defined position. It is essential for cleaning data where you need to isolate parts of a string based on fixed lengths or positions, such as extracting product codes or trimming inconsistent whitespace.
What You'll Need
- Microsoft Excel (with Power Query enabled) or Power BI Desktop.
- A dataset containing text columns that require substring extraction.
- Basic understanding of zero-based indexing in programming logic.
Step-by-Step
- Load your data into Power Query: In Excel, go to the Data tab and select "Get Data" > "From Table/Range." In Power BI, click "Transform Data" after loading your source. This opens the Power Query Editor window.
- Select the target column: Click on the header of the text column you want to modify. Ensure the data type for this column is set to "Text" by right-clicking the header and selecting "Change Type" > "Text." If it is not text, the function will return an error.
- Open the Custom Column dialog: Navigate to the "Add Column" tab in the ribbon. Click on "Custom Column." This is where you will write the M code formula.
- Define the new column name: In the "New column name" field, enter a descriptive name, such as "Extracted_Text" or "Middle_Part." This helps keep your query organized.
- Write the Text.Middle formula: In the "Custom column formula" box, type the following structure:
= Text.Middle([ColumnName], StartPosition, Length). Replace[ColumnName]with the actual name of your source column (including square brackets),StartPositionwith the index where extraction begins, andLengthwith the number of characters to extract. - Example usage: If you have a column named "FullCode" with values like "ABC123XYZ" and you want to extract "123," use:
= Text.Middle([FullCode], 3, 3). The start position is 3 because indices are zero-based (A=0, B=1, C=2, so '1' is at index 3). The length is 3 because you want three characters. - Click OK: Press the "OK" button to apply the formula. A new column will appear in your preview pane showing the extracted substrings.
- Verify results: Check several rows to ensure the extraction matches your expectations. Look for any "null" or error values which indicate issues with the input data.
- Close and Load: Once satisfied, go to the "Home" tab and click "Close & Load." Your transformed data will be returned to Excel or Power BI.
Common Mistakes
One frequent error is using one-based indexing instead of zero-based indexing. Unlike Excel worksheet functions, Power Query M language starts counting at 0. If you want to start at the first character, the start position must be 0, not 1. Another common mistake is ignoring data types. If the source column contains numbers or dates, Text.Middle will fail unless you convert them to text first using Text.From().
Users also often miscalculate the length parameter. Remember that the length is the number of characters to take, not the ending index. For example, to get characters from index 2 to 5, the length is 4 (indices 2, 3, 4, 5).
Tips
Combine Text.Middle with other functions for dynamic extraction. Use Text.Length() to calculate the end of a string if you don't know the exact length. For instance, to remove the last two characters, you might use Text.Middle([Column], 0, Text.Length([Column]) - 2).
If you are extracting based on delimiters rather than fixed positions, consider using Text.Split() or Text.BetweenDelimiters() instead. These are often more robust when data formatting varies slightly between rows.
Always test your formula on a small subset of data before applying it to millions of rows. Power Query processes data efficiently, but complex nested formulas can slow down refresh times if not optimized.
Troubleshooting
If you see an error saying "Expression.Error: We cannot convert a value of type Number to type Text," check your source column's data type. Right-click the column header and change it to Text, or wrap the column reference in Text.From() within your formula.
If the result is null, verify that the start position and length do not exceed the bounds of the string. While Text.Middle handles out-of-bounds requests gracefully by returning available characters, unexpected nulls may arise if the entire row context is invalid or if the column name in the formula does not match the actual column name exactly (case-sensitive).
For errors regarding syntax, ensure all parentheses are closed and commas separate arguments correctly. Copy-pasting formulas from web sources can sometimes introduce smart quotes; replace them with standard straight quotes.
Frequently Asked Questions
Is Text.Middle case-sensitive?
No, the function itself does not care about case. However, the column names referenced in the formula are case-sensitive in Power Query. Ensure [MyColumn] matches the actual header capitalization.
What happens if I request more characters than exist?
Text.Middle is forgiving. If the specified length exceeds the remaining characters in the string, it simply returns all available characters from the start position to the end of the string without throwing an error.
Can I use variables for start position and length?
Yes, you can define steps earlier in your query to calculate positions dynamically. For example, find the index of a delimiter using Text.PositionOf() and use that result as the start position for Text.Middle.
Does this work in Power BI Service?
Yes, once the query is published, the transformation logic runs identically in the Power BI Service during scheduled refreshes. There are no differences in how Text.Middle behaves between desktop and service environments.