Home » excel » excel – Get sub-parts of text in cell

excel – Get sub-parts of text in cell

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a spreadsheet in Excel with one product per row and I would like to get the height and the width of each item according to the text in a column. I have dimensions text in the A column:

8" H x 8" W 
2.5" H x 3.5" W 
per side 8" H x 8" W 
1 color left side 1" H x 3" W 

and would like to put the Height in the column (B) and the Width in the column (C). Like this:

              (A)                   (B)                (C)
8" H x 8" W                         8                  8
2.5" H x 3.5" W                     2.5                3.5
per side 8" H x 8" W                8                  8
1 color left side 1" H x 3" W       1                  3

I started with this snippet but I can’t figure out how to get the desired part:

Sub numberExtractor()
Dim Cell As Integer
For Cell = 2 To 449

    If InStr(Cells(Cell, 17), """ H") > 0 Then
        Cells(Cell, 18).Value = Left(Cells(Cell, 17), InStr(Cells(Cell, 17), " ") - 1)
    End If
    If InStr(Cells(Cell, 17), """ W") > 0 Then
        Cells(Cell, 19).Value = Right(Cells(Cell, 17), InStr(Cells(Cell, 17), " ") + 2)
    End If

Next Cell
End Sub
How to&Answers:

Logic:

  1. Use a unique delimiter. I am using SIDZ.
  2. Replace " W by ""
  3. Replace " H x by SIDZ
  4. First split on SPACE and then on the unique delimiter

Try this.

Option Explicit

Sub Sample()
    Dim rng As Range, aCell As Range
    Dim Ar
    Dim Ht As Double, Wt As Double
    Dim sTemp As String, sDelim As String
    Dim i As Long

    sDelim = "SIDZ"

    Set rng = Range("A1:A4")

    For Each aCell In rng
        sTemp = aCell.Value
        sTemp = Replace(Replace(sTemp, """ W ", ""), """ H x ", sDelim)

        Ar = Split(sTemp)

        For i = LBound(Ar) To UBound(Ar)
            If Ar(i) Like "*" & sDelim & "*" Then
                aCell.Offset(, 1).Value = Split(Ar(i), sDelim)(0)
                aCell.Offset(, 2).Value = Split(Ar(i), sDelim)(1)
            End If
        Next i
    Next aCell
End Sub

enter image description here

Answer:

With formulae, to be copied down to suit:

in B1:

=IF(FIND(" H",SUBSTITUTE(A1,"""",""))>4,MID(SUBSTITUTE(A1,"""",""),FIND(" ",SUBSTITUTE(A1,"""",""),FIND(" H",SUBSTITUTE(A1,"""",""))-4)+1,FIND(" ",SUBSTITUTE(A1,"""",""),FIND(" ",SUBSTITUTE(A1,"""",""),FIND(" H",SUBSTITUTE(A1,"""",""))-4)+1)-FIND(" ",SUBSTITUTE(A1,"""",""),FIND(" H",SUBSTITUTE(A1,"""",""))-4)),LEFT(SUBSTITUTE(A1,"""",""),FIND(" ",SUBSTITUTE(A1,"""",""))))  

in C1:

=RIGHT(SUBSTITUTE(SUBSTITUTE(A1,"""","")," W",""),LEN(SUBSTITUTE(SUBSTITUTE(A1,"""","")," W",""))-FIND(" x ",SUBSTITUTE(SUBSTITUTE(A1,"""","")," W",""))-2)  

Photo courtesy @Siddharth Rout