Excel VBA解析列,提取所有子字符串

时间:2018-08-06 18:27:32

标签: excel vba

我正在尝试解析一个包含每个单元格中以下格式的数据的列-

拉:test1

拉:test2 |拉:test3 | .....

其他:等等...

我只想抓取每个“ Pull:test”,然后在新工作表中的每一行中放置1,如下所示,并忽略单元格中所有不以“ pull:”开头的部分--

拉:test1

拉:test2

拉:test3

...

到目前为止,我所获得的只是拉整整列并粘贴到同一电子表格中,我不确定如何将每个单元格中的项目分成各自的行。我也无法正确地将其拉到其他工作表(注释了我的尝试)

Sub InStrDemo()
Dim lastrow As Long
Dim i As Integer, icount As Integer

'Sheets.Add.Name = "TEST"

lastrow = ActiveSheet.Range("A10000").End(xlUp).Row
For i = 1 To lastrow
    If InStr(1, LCase(Range("E" & i)), "pull:") <> 0 Then
        icount = icount + 1
        'Sheets("TEST").Range("A" & icount & ":E" & icount) = Worksheets("SearchResults").Range("A" & i & ":E" & i).Value
        Range("L" & icount) = Range("E" & i).Value
    End If
Next i
End Sub

1 个答案:

答案 0 :(得分:0)

未经测试,写在手机上。

Option Explicit

Sub testDemo()

Dim sourceSheet as worksheet
Set sourceSheet = ActiveSheet ' would be more reliable to qualify the workbook and worksheet by name'

Dim outputSheet as worksheet
Set outputSheet = thisworkbook.worksheets.add

Dim lastRow As Long

lastrow = sourceSheet.Range("A10000").End(xlUp).Row

' I assume column E needs to be parsed'
Dim arrayOfValues() as variant
arrayOfValues = sourceSheet.range("E1:E" & lastRow)

Dim rowIndex as long
Dim columnIndex as long
Dim splitString() as string
Dim cumulativeOffset as long

Dim toJoin(0 to 1) as string
toJoin(0) = "pull: test" ' Might speed up string concatenation below'

Dim outputArray() as string

With outputsheet.range("A1") ' The first row you want to start stacking from'

For rowIndex = 1 to lastRow

' Single dimensional, 0-based array'
splitString = VBA.strings.split(vba.strings.lcase$(arrayOfValues(rowIndex,1)), "pull: test",-1, vbbinarycompare)

Redim outputArray(1 to (ubound(splitString)+1), 1 to 1)

For columnIndex = lbound(splitString) to ubound(splitString)
toJoin(1) = splitString(columnIndex)

Outputarray(columnIndex+1,1) = VBA.strings.join(toJoin, vbnullstring)

Next columnIndex

'Instead of splitting upon a delimiter, then prepending the delimiter to each array element (as is done above), you could repeatedly call instr(), use mid$() to extract the sub-string, then increase the argument passed to the "Start" parameter in instr() (effectively moving from start to end of the string) -- until instr() returns 0. Then move on to the next string in the outer loop.'

.offset(cumulativeOffset,0).resize(Ubound(outputArray, 1), 1).value2 = outputArray

cumulativeOffset = cumulativeOffset + ubound(splitString)

Next rowIndex

End Sub