InStr和InStrRev没有正确地将位置返回到Mid

时间:2015-09-20 08:53:47

标签: excel vba excel-vba

Sub nosaukuma_splits()
    Dim ws As Worksheet
    Dim p

    Set ws = ThisWorkbook.Worksheets("splits_name")
    RowCount = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    For i = 1 To RowCount
        vertiba = ws.Cells(i, 2)
        pzime = InStr(vertiba, " -")
        ozime = InStrRev(vertiba, "- ")

        ws.Cells(i, 3) = Mid(vertiba, 1, pzime)
    Next i

    For i = 1 To RowCount
        vertiba = ws.Cells(i, 2)
        pzime = InStr(vertiba, " -")
        ozime = InStrRev(vertiba, "- ")

        ws.Cells(i, 4) = Mid(vertiba, pzime, ozime - pzime)
    Next i

End Sub

为什么我的代码不会在第23行执行?可能是什么原因?

单元格文字看起来像(1text) - (2text) - (3text)

我需要在分隔的单元格中获取(1text)(2text)

1 个答案:

答案 0 :(得分:0)

使用VBA Split function将文本值分隔为变量数组,然后将所需数组的元素返回到工作表。

Sub nosaukuma_splits()
    Dim ws As Worksheet
    Dim i As Long, rc As Long, vTXTs As Variant

    Set ws = ThisWorkbook.Worksheets("splits_name")

    With ws
        rc = .Cells(Rows.Count, "A").End(xlUp).Row
        For i = 1 To rc
            vTXTs = Split(.Cells(i, 2).Value2, " - ")
            .Cells(i, 3).Resize(1, 2) = Array(vTXTs(0), vTXTs(1))
        Next i
    End With

End Sub

就原始代码而言,在确定Mid function中的起点和长度时,您没有正确补偿分隔符的长度(例如“ - ”或“ - ”)。

Sub nosaukuma_splits_pirmais()
    Dim ws As Worksheet
    Dim i As Long, rc As Long, pzime As Long, ozime As Long, vertiba As String

    Set ws = ThisWorkbook.Worksheets("splits_name")
    rc = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    For i = 1 To rc
        vertiba = ws.Cells(i, 2)
        pzime = InStr(1, vertiba, " -")
        ozime = InStr(pzime, vertiba, "- ")
        ws.Cells(i, 3) = Trim(Mid(vertiba, 1, pzime))
    Next i

    For i = 1 To rc
        vertiba = ws.Cells(i, 2)
        pzime = InStr(1, vertiba, " -") + 2
        ozime = InStr(pzime + 1, vertiba, "- ")
        ws.Cells(i, 4) = Trim(Mid(vertiba, pzime, ozime - pzime))
    Next i

End Sub

我放弃了InStrRev function并使用了hte first delimiter的位置来开始使用InStr搜索第二个分隔符的位置。

结果中似乎还有一些前导/尾随空格被放回到工作表中,因此我添加了Trim function来处理这些空间。