在vba中用破折号分隔字符

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

在这里输入图像说明

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 

你可以这样做:

 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中有一个内置function来分隔分隔文本TextToColumns
我们需要的是只使用它来分隔string,特别是如果你只有一个分隔符。

实际上,如果希望评估列A中的所有数据,则不需要检查最后一行的值。 所以下面将工作得很好。

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

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

 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 

这将一次完成(即使从debugging窗口),并不限于是4列(这是你在post中要求的),而是根据需要占用多less列 – 将分割string

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

我的testing数据是在第9行A列中,如果需要的话,很容易将其放入循环中。

注意:这是作为其他答案的替代方式提供的,我不以任何方式说这是唯一的或最好的方法,如果你正在做多行,你最好使用Excels内置的文本到列function由@ L42