在每个第二个括号

时间:2018-03-14 03:46:55

标签: excel vba excel-vba

尝试在第二个括号后获取值,我尝试使用我创建的这个值,但它不能正常工作并且变得更复杂,而我在每行中有更多括号..任何想法。我上传了几张图片以了解输入和输出。

Sub stringtest()

    Dim text As String, i As Long, firstbracket As Long, secondbracket As Long
    Dim extractTest As String, y As Long

    y = 1
    For i = 1 To 10

        text = Worksheets("Sheet1").Cells(i, 1).Value
        firstbracket = InStr(1, text, "[")
        secondbracket = InStr(firstbracket + 1, text, "]")
        extractTest = Mid(text, firstbracket + 1, secondbracket)

        Worksheets("Sheet1").Cells(y, 2).Value = extractTest
        y = y + 1

    Next i

End Sub

enter image description here enter image description here

3 个答案:

答案 0 :(得分:5)

尝试按第二个括号分割,然后使用Option Explicit Public Sub GetStringAfter2ndBracketInSequentialColumns() Dim i As Long, j As Long, nextRow As Long, ub As Long, lr As Long Dim extract As Variant, found As Long, nextCol As Long With Sheet1 lr = .UsedRange.Rows.Count nextRow = 1 nextCol = 2 For i = 1 To lr extract = Split(.Cells(i, 1).Value2, "]") ub = UBound(extract) If ub > 0 Then For j = 0 To ub If Len(extract(j)) > 0 Then If Left(extract(j), 1) <> "[" Then found = InStr(1, extract(j), "[") If found = 0 Then found = Len(extract(j)) + 1 .Cells(nextRow, nextCol).Value2 = Left(extract(j), found - 1) nextRow = nextRow + 1 If nextRow > lr Then nextRow = 1 nextCol = nextCol + 1 End If End If End If Next j End If Next i End With End Sub 确定字符串的长度

Timers (with 100,000 rows)

0.824 secs - TextToColumns  (0.81054, 0.82812) - Output: same row split to many cols
1.679 secs - Split cells    (1.66796, 1.64453) - Output: sequentially by rows, then cols
3.757 secs - ArrayList      (3.69140, 3.78125) - Output: sequentially in one column

测试结果:

https://github.com/aframevr/aframe/blob/master/src/components/collada-model.js

这是分割后的一个字符串(单元格A1)的样子

Results

修改:目前为止提供的所有解决方案的测量结果:

{{1}}

答案 1 :(得分:3)

这是一个简短而快速的方法

Sub main()
    With Range("A1", Cells(Rows.Count, 1).End(xlUp))
        .Replace what:="[*]", replacement:="|", lookat:=xlPart
        .TextToColumns DataType:=xlDelimited, Other:=True, OtherChar:="|"
        .Columns(1).Delete xlToLeft
    End With
End Sub

答案 2 :(得分:1)

这里使用ArrayList

的方法略有不同
Dim rng As Range
Dim arl As Object
Dim strVal
Dim i As Long
Set arl = CreateObject("System.Collections.ArrayList")
For Each rng In Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)
    strVal = Split(Replace(rng.Value, "[", "]"), "]")
    For i = 2 To UBound(strVal) Step 2
        arl.Add CStr(strVal(i))
    Next i
Next rng
For i = 0 To arl.Count - 1
    Range("B" & i + 1).Value = arl.Item(i)
Next i
Set arl = Nothing