I have a set of descriptions that contain ID numbers arranged into a column. For example:
This is a description with the ID number in it ID12345.
This is a description ID66666 with the ID number in it.
This is ID99999 a description with the ID number in it.
The Id numbers are always in the format “IDXXXXX” I’d like to somehow trim away all the text in each of these cells and leave just that ID number.
Can this be somehow done by finding a string like “ID?????” and setting that to a variable, then replacing the contents of the cell with that variable? Or by erasing all characters in a cell -except- for “ID?????”
Any help would be appreciated, thanks.
This code I wrote for you will iterate through all items in Column A. It will split all the words in each cell into an array. If the word is 7 or 8 characters long then it could potentially be an
IDxxxxx. It will perform a few checks to see if it really matches an
IDxxxxx syntax. In case it does it will replace the contents of the cell with just the ID dropping all the remaining text.
Sub ReplaceContentWithIDs() Dim ws As Worksheet Set ws = Sheets("Sheet1") ' or your sheet name Dim rng As Range Dim i&, lr&, j& Dim arr Dim str$ lr = ws.Range("A" & Rows.Count).End(xlUp).Row ' starting from 1 - if you have headers change to 2 For i = 1 To lr Set rng = ws.Range("A" & i) arr = Split(CStr(rng.Value), " ") For j = LBound(arr) To UBound(arr) str = arr(j) If (Len(str) = 7) Or (Len(str) = 8) Then If (StrComp(Left(str, 2), "ID", vbTextCompare) = 0) And _ IsNumeric(Right(Left(str, 7), 5)) Then ' found it If Len(str) = 8 Then rng.Value = Left(str, 7) ElseIf Len(str) = 7 Then rng.Value = str End If End If End If Next j Set rng = Nothing Next i End Sub
I took this as a challenge to my intellect, and given that it is the end of the day, after seeing the formulas by Aladdin and pgc01 on Mr Excel forums I did a little work and came up with this CSE (Array formula):
I also had some luck with this CSE Array formula: