在单元格中获取文本的子部分

时间:2014-09-10 15:11:28

标签: excel vba parsing excel-vba

我在Excel中有一个电子表格,每行有一个产品,我想根据列中的文字得到每个项目的高度和宽度。我在A栏中有尺寸文字:

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 

并希望将高度放在列(B)中,将宽度放在列(C)中。像这样:

              (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

我从这个片段开始,但我无法弄清楚如何获得所需的部分:

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

2 个答案:

答案 0 :(得分:2)

逻辑:

  1. 使用唯一的分隔符。我正在使用SIDZ
  2. " W替换为""
  3. " H x替换为SIDZ
  4. 首先在SPACE上拆分,然后在唯一分隔符
  5. 上拆分

    试试这个。

    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

答案 1 :(得分:1)

使用公式,将其复制以适应:

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,"""",""))))  
C1中的

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

Photo courtesy @Siddharth Rout