【问题标题】:Separate characters by dashes in vba在vba中用破折号分隔字符
【发布时间】:2015-04-28 20:09:13
【问题描述】:

我试图在 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 excel split


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

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

        我的测试数据位于第 9 行的 A 列中,如果需要,可以轻松地将其放入循环中。

        注意:这是作为其他答案的替代方法提供的,我绝不是说这是唯一或最好的方法,如果您正在做多行,最好使用 Excels 内置文本到列@L42 发布的函数

        【讨论】:

          猜你喜欢
          • 2012-01-20
          • 2011-12-05
          • 1970-01-01
          • 2015-07-27
          • 1970-01-01
          • 1970-01-01
          • 2016-12-17
          • 2012-05-12
          • 2016-06-29
          相关资源
          最近更新 更多