使用Excel行作为分隔符的拆分功能

时间:2015-07-09 13:21:15

标签: arrays excel vba excel-vba split

我有一个使用过的列,我想创建一个数组,使用单元格/行作为分隔符将此列拆分为多个项目。

类似于:MyArray = Split(Excel.Workbooks(X).Worksheets(X).UsedRange.Columns(X), Row)

我收到Type Mismatch错误。

是否有可能或有任何变通方法?

2 个答案:

答案 0 :(得分:0)

Split()函数的正确语法是Split([String], [Delimiter String])。要在您的示例中完成此操作,最好创建一个循环:

http://www.homeandlearn.org/the_split_function.html

Sub SplitIt()
    Dim LastRow As Long, txt As String, i as Integer, CurRow as Long, MyArray as Variant, ws as Worksheet
    Set ws = Sheets("Name of Sheet")
    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
    For CurRow = 1 to LastRow
        MyArray = Split(ws.Range("A" & CurRow).Value, "[Delineation String]")
        For i = 0 to UBound(MyArray)
            ws.Cells(CurRow, i + 2).Value = MyArray(i)
        Next i
    Next CurRow
End Sub

例如,如果列A有三个单词由“空格”分隔,并且您使用“空格”作为“划分字符串”,那么您将获得:

           A                B        C         D
1  Alpha Bravo Charlie    Alpha    Bravo    Charlie
2  Delta Echo Foxtrot     Delta    Echo     Foxtrot

答案 1 :(得分:0)

如果您正在寻找拆分单元格内容并希望它位于工作表/工作簿中的某个位置,则可以尝试此操作。

Sub split_1()
Dim myarray() As String
Dim str As String
str = ThisWorkbook.Sheets("Sheet1").Range("A1").Value
'str = "this,sentence,seperated,by,comma"
   myarray = Split(str, ",")

   For i = LBound(myarray) To UBound(myarray)
      Debug.Print myarray(i) 'here you can copy to other cells/sheets, etc.,
    Next
End Sub