如何将一个单元格内的事物列表分成几个单元格?

时间:2016-09-08 14:50:17

标签: excel excel-vba vba

我的这个单元格包含一系列内容,例如:

[dogs, cats, mice, cows, horses]

我想在不同的细胞中分开它们:

[dogs]
[cats]
[mice]
[cows]
[horses]

可以这样做吗?

3 个答案:

答案 0 :(得分:1)

您可以在VBA

中轻松完成此操作
Sub splitString ()
    Dim ran, splitS() As String
    ran = Range("A1")
    splitS() = Split(ran, ",")
    For j = LBound(splitS) To UBound(splitS)
    Range("B" & (j + 1)) = splitS(j)
    Next j
End Sub

如果您还想要方括号,请使用以下代码:

Sub splitStringWithSquareBrackets()
    Dim ran, splitS() As String
    ran = Range("A1")
    ran = Right(ran, Len(ran) - 1)
    ran = Left(ran, Len(ran) - 1)
    splitS() = Split(ran, ",")
    For j = LBound(splitS) To UBound(splitS)
    Range("B" & (j + 1)) = "[" & splitS(j) & "]"
    Next j
End Sub

答案 1 :(得分:0)

这样做 - 你必须在运行之前选择带有单元格的单元格,并假设两端都有封闭的括号(“[”和“]”)。

我现在能得到最好的答案..

Sub ImAmazing()
Dim sString As String, i As Long

If Trim(ActiveCell.Value) = "" Then Exit Sub

ActiveCell.Value = Mid(ActiveCell.Value, 2, Len(ActiveCell.Value) - 2)

Do Until InStr(ActiveCell.Value, ",") = 0
    i = i + 1
    Cells(ActiveCell.Row + i, ActiveCell.Column).Value = "[" & Left(ActiveCell.Value, InStr(ActiveCell.Value, ",") - 1) & "]"
    ActiveCell.Value = Right(ActiveCell.Value, (Len(ActiveCell.Value) - InStr(ActiveCell.Value, ",") - 1))
Loop

ActiveCell.Value = "[" & ActiveCell.Value & "]"

End Sub

答案 2 :(得分:0)

单元格中的数据 A1

Sub dural()
    Dim s As String, i As Long

    s = Range("A1").Value
    s = Mid(s, 2, Len(s) - 2)
    ary = Split(s, ", ")
    i = 2

    For Each a In ary
        Cells(i, "A").Value = "[" & a & "]"
        i = i + 1
    Next a
End Sub

enter image description here