在vba中用破折号分隔字符

时间:2015-04-28 20:09:13

标签: excel vba excel-vba split

我试图在VBA中用( - )破折号分隔字符,然后将其粘贴到B列。所以在我的A列中我有TOM-JAY-MOE-XRAY。现在,如果我想将它拆分并粘贴到4个不同的列中,如列B = TOM,C = JAY,依此类推。这是我的代码和图像,以便更好地理解。

enter image description here

Sub x()
    Dim sheet As Worksheet
    Set sheet = ActiveWorkbook.Worksheets("Sheet1")
    For x = 1 To sheet.Range("A" & sheet.Rows.Count).End(xlUp).Row
        sheet.Range("A", "B", "C", "D" & x) = InStr(1, sheet.Cells(x, 1), "-")
    Next x
End Sub

3 个答案:

答案 0 :(得分:1)

你可以这样做:

With Sheets("SheetName")
    Dim lr As Long
    lr = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & lr).TextToColumns Destination:=.Range("B1") _
        , DataType:=xlDelimited, Other:=True, OtherChar:="-"
End With

Excel中有一个内置功能,用于分隔分隔文本TextToColumns 我们需要的是只使用它来分隔字符串,特别是如果你只有1个分隔符。

实际上,如果您希望评估A列中的所有数据,则不需要使用值检查最后一行。所以下面就可以了。

With Sheets("SheetName")
    .Range("A:A").TextToColumns Destination:=.Range("B1") _
        , DataType:=xlDelimited, Other:=True, OtherChar:="-"
End With

答案 1 :(得分:0)

您可以使用VBA Split功能拆分分隔文本。这是一个基本的例子:

Sub test()

    Dim MyArray() As String

    ' use the VBA split function to split the string into array of strings
    ' the second function parameter identifies the delimiter
    MyArray() = Split("TOM-JAY-MOE-XRAY", "-")

    ' here I iterated the array and printed to the debug window.
    For i = LBound(MyArray) To UBound(MyArray)
        Debug.Print "Word " & i & "=" & MyArray(i)
    Next i

End Sub

答案 2 :(得分:0)

这将一次完成(甚至从调试窗口),并且不限于4列(这是您在帖子中要求的),而是只占用所需数量的列。多少 - 将分割字符串

Range("B9").Resize(1,ubound(Split(Range("A9").Text,"-"))+1) = Split(Range("A9").Text,"-")

我的测试数据位于第9行A列,如果需要,很容易将其放入循环中。

注意:这是作为其他答案的替代方式提供的,我并不是说这是唯一或最好的方法,如果你要做多行,最好使用Excel内置文本到列功能由@ L42发布