在 vba 中用破折号分隔字符

Separate characters by dashes in vba

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

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

您可以使用 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

你可以这样做:

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

这将一次性完成(即使是调试 window)并且不限于 4 列(这是您在 post 中要求的),而是只需要根据需要增加尽可能多的列 - 将拆分字符串

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

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

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

编辑post