String中的字符串,通过搜索特定文本的每个匹配项并过滤到其他单元格

时间:2017-12-06 11:41:43

标签: excel string excel-vba vba

Summary : Using vba-excel Looping through a single cell of text , finding 
and taking  out  each nth occurrence of <li> to </li > into each individual 
cell 

之前

单个excel单元格(例如A1)包含

<li>
  <ahref="xxxx">
  <imgsrc=""yyy">
  </a>
</li>

<li>
  <ahref="xxxx">
  <imgsrc=""yyy">
  </a>
</li>

结果(之后):

单元格A2

<ahref="xxxx">
<imgsrc=""yyy">

单元格A3

<ahref="xxxx">
<imgsrc=""yyy">

非常感谢; D

到目前为止我做了什么

'myrow is already pre-define previous , basically row number fetch during 
 loopping

Dim newi As String
Dim texti as string 

i = MyRow     texi = cell(i,1)

'not sure if this is correct , trying to find each
For Each item In Texti 
Cells(i, 13) = item("<a href=")
Cells(i, 14) = item("<img src=")
newi = Cells(i, 13).Value + "  " + Cells(i, 14).Value
Next

再次感谢您提前帮助我,坚持这个〜!

1 个答案:

答案 0 :(得分:0)

试试这个:

Sub StringExtract()

Dim iLength As Integer, iLoopCounter As Integer, iInnerLoopCounter As Integer
Dim sRemString As String
Dim iLastRow As Integer

iLength = Len(Range("A1"))

For iLoopCounter = 1 To iLength

    If (Mid(Range("A1"), iLoopCounter, 4) = "<li>") Then

        For iInnerLoopCounter = iInnerLoopCounter + 4 To iLength

            If (Mid(Range("A1"), iInnerLoopCounter, 5) = "</li>") Then

                sRemString = Mid(Range("A1"), iLoopCounter + 5, iInnerLoopCounter - iLoopCounter - 6)

                iLastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1

                Cells(iLastRow, "A").Value = sRemString

                Exit For

            End If

        Next iInnerLoopCounter

    End If

Next iLoopCounter
End Sub

可能不是最快的方法,但在这种情况下它应该有效。我无法弄清楚,为什么</a>也应该被排除在外。如果需要,请在此行中将-6的整数增加到您的需要:

sRemString = Mid(Range("A1"), iLoopCounter + 5, iInnerLoopCounter - iLoopCounter - 6)