Removing Spaces from Certain Numbers in Excel Text Cells Containing Letters

Abstract: Remove spaces between digits in mixed text cells using REGEXREPLACE or VBA to clean historical data without merging words.

Created: 2026-08-28 by

To remove spaces from specific numbers within Excel text cells, use the REGEXREPLACE function in Google Sheets or a VBA macro in Excel. These methods target numeric sequences while preserving surrounding letters and punctuation, which is essential for cleaning historical data like wills without altering the overall structure of the text string.

Understanding the Data Challenge

When working with digitized historical documents, such as early modern wills from the Internet Archive, text extraction often introduces inconsistent spacing. You might encounter entries where numbers are separated by spaces (e.g., "10 00 pounds") while other parts of the text remain intact. Standard space removal functions like SUBSTITUTE(A1, " ", "") are too aggressive because they strip all spaces, merging words together and rendering the text unreadable. The goal is to identify patterns where digits are followed by a space and another digit, then remove that internal space while leaving single-digit numbers and alphabetic characters untouched. This distinction is critical when dealing with large datasets where manual correction is impossible. You need a programmatic approach that recognizes numerical boundaries. For instance, you want to convert "Item 5 00" to "Item 500" but leave "Item 5" alone. This requires looking ahead in the string to see if a space is sandwiched between two numbers.

Why Simple Functions Fail

Many users initially try using the TRIM function. However, TRIM only removes leading and trailing spaces and collapses multiple internal spaces into one. It does not remove spaces between digits. Similarly, SUBSTITUTE replaces every instance of a space character. If your cell contains "John Smith 10 00", applying SUBSTITUTE results in "JohnSmith1000", which destroys the semantic meaning of the name. Therefore, a more sophisticated pattern-matching tool is required.

Solution for Google Sheets: REGEXREPLACE

Google Sheets provides a powerful built-in function called REGEXREPLACE that allows you to search for complex patterns using regular expressions. This is the most efficient method if you have access to Google Sheets. The syntax is =REGEXREPLACE(text, regular_expression, replacement). To remove spaces between digits, you need a regular expression that looks for a digit (\d), followed by a space ( ), followed by another digit (\d). The replacement should be an empty string, effectively deleting the space. The formula is:
=REGEXREPLACE(A1, "(\\d) (\\d)", "$1$2")
Here, (\\d) captures a digit. The parentheses create a capture group. The space matches the literal space character. The second (\\d) captures the next digit. In the replacement field, $1$2 inserts the first captured digit immediately followed by the second, removing the space in between. Note that backslashes must be escaped with another backslash in Google Sheets formulas. If you also need to handle cases where there might be multiple spaces between digits, you can modify the regex to (\\d) + (\\d). This ensures robustness against irregular formatting. For related text manipulation tasks, you might also find it useful to learn how to Remove Numbers from Text in Excel, which complements this technique by isolating alphanumeric components.

Solution for Microsoft Excel: VBA Macro

Excel does not have a native REGEXREPLACE function in its standard interface, although newer versions may introduce it via dynamic arrays. For now, the most reliable method is using Visual Basic for Applications (VBA). This involves creating a User Defined Function (UDF) that applies regular expressions to your cells. First, press Alt + F11 to open the VBA editor. Insert a new module and paste the following code. This code correctly declares variables and uses the RegExp object to perform the replacement.
Function RemoveSpacesBetweenNumbers(rng As Range) As String
    Dim regEx As Object
    Set regEx = CreateObject("VBScript.RegExp")
    
    With regEx
        .Global = True
        .IgnoreCase = True
        .Pattern = "(\d) (\d)"
        RemoveSpacesBetweenNumbers = .Replace(rng.Value, "$1$2")
    End With
    
    Set regEx = Nothing
End Function
Once saved, you can use this function in your worksheet just like any other formula: =RemoveSpacesBetweenNumbers(A1). This approach is highly flexible and can be modified to handle other patterns, such as removing spaces after commas or before periods. It is important to ensure that the VBA script references the correct library. In older Excel versions, you might need to enable the "Microsoft VBScript Regular Expressions 5.5" reference under Tools > References in the VBA editor. However, the CreateObject method used above typically works without explicit reference settings, making it portable across different Excel installations. For those managing complex workflows, understanding how to Move Rows Based on Matching Cells Across Two Worksheets can help automate the process of cleaning and organizing your historical data after the text has been standardized.

Alternative Manual Approaches

If you cannot use scripts or advanced functions, you might consider a multi-step manual process. First, use the Find and Replace feature (Ctrl + H) to replace common number-space-number patterns. For example, replace " 0 " with "0". Repeat this for " 1 " through " 9 ". This is tedious and error-prone but requires no coding. Another alternative is using Power Query in Excel Pro. You can load the data into Power Query, add a custom column with a M formula that uses Regex.Replace, and then load the cleaned data back into Excel. This is ideal for repeatable data cleaning pipelines.

Frequently Asked Questions

Can I use this method on entire columns at once?

In Google Sheets, you can apply the REGEXREPLACE formula to a range by dragging it down or using an array formula wrapped in {}. In Excel, the VBA UDF can be dragged down a column just like a standard function. For bulk processing in Excel, consider using Power Query to apply the transformation to the entire table source automatically.

What if the numbers have decimal points?

The current regex (\d) (\d) will treat the dot as a non-digit separator, so "10. 5" would become "10.5" correctly if the space is between the digit and the dot? No, it targets digit-space-digit. To handle decimals like "10 .5", you might need a more complex pattern like (\d+) \.? ?(\d+). Test your specific format carefully before applying to large datasets.

Does this work for negative numbers?

Standard patterns do not include the minus sign. If you have "-10 00", the regex won't match the space after the minus unless you adjust the pattern to include optional signs. You would need to expand the regex to ([-]?\d) (\d) to capture negative signs as part of the first number group.

How do I revert changes if I make a mistake?

If you use formulas in new columns, simply delete those columns to revert. If you use VBA to overwrite original data, always save a backup copy of your workbook before running macros. Excel’s undo history is limited for VBA operations, so prevention is key.

Are there any performance issues with large datasets?

VBA functions can slow down Excel if applied to tens of thousands of rows because they execute row-by-row. Google Sheets handles REGEXREPLACE more efficiently in cloud environments. For very large Excel files, Power Query is significantly faster than VBA UDFs as it processes data in batches.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More