如何使用UBound拆分列中的字符串并将分隔的字符串放到VBA中的另一列

时间:2016-01-12 10:00:17

标签: excel vba excel-vba

我有一个电话号码栏(比如D列),其中一些用分号(;)或冒号(,)分隔两个电话号码。
我想拆分两个电话号码,然后将第二个电话号码放到左边的一列(比如B列),将第一个放在原来的D列单元格中。如果单元格中只有一个电话号码,请不要管它 我明白它可能会使用UBound和Split Array?但是如何?
有人可以帮帮我吗? 谢谢。

3 个答案:

答案 0 :(得分:1)

如果您完全确定他们只能在单元格中使用两个电话号码,这应该可以解决问题,或者至少它对我来说是这样的:

Option Explicit

Sub test()

Dim chkRng As Range
Dim cell As Range
Dim arr As Variant

Set chkRng = Range("D1:D" & (Range("D" & Rows.Count).End(xlUp).Row))

For Each cell In chkRng

    If InStr(1, cell.Value, ",") > 0 Then

        arr = Split(cell.Value, ",")

    ElseIf InStr(1, cell.Value, ";") > 0 Then

        arr = Split(cell.Value, ";")

    Else
        GoTo continue

    End If

    cell.Offset(, -2).Value = Trim(arr(1))
    cell.Value = Trim(arr(0))

continue:
Next cell

End Sub

答案 1 :(得分:1)

试试这个

Sub rep()

For Each c In Sheets("Sheet1").Range("D1:D65").Cells ' Change the range that you want

    If InStr(c.Value, ",") > 0 Then

        phonNumb = Split(c, ",")
        Range("D" & c.Row) = phonNumb(0)
        Range("C" & c.Row) = phonNumb(1)

    ElseIf InStr(c.Value, ";") > 0 Then

        phonNumb = Split(c, ";")
        Range("D" & c.Row) = phonNumb(0)
        Range("C" & c.Row) = phonNumb(1)
    End If

Next c

End Sub

答案 2 :(得分:0)

这可能是一种更简单的方法,但您可以使用Instr函数来定位分号(;)或逗号(,),然后将它们分开。例如,以下工作:

Sub SeparateNumbers()

Dim Rng As Range

Set Rng = ActiveSheet.Range("D1:D" & ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row)

For Each Cell In Rng
    If InStr(1, Cell.Value, ";") Then
        Cell.Offset(0, -2).Value = Trim(Mid(Cell.Value, InStr(1, Cell.Value, ";") + 1, (Len(Cell.Value) - (InStr(1, Cell.Value, ";")))))
        Cell.Value = Mid(Cell.Value, 1, InStr(1, Cell.Value, ";") - 1)
    End If
    If InStr(1, Cell.Value, ",") Then
        Cell.Offset(0, -2).Value = Trim(Mid(Cell.Value, InStr(1, Cell.Value, ",") + 1, (Len(Cell.Value) - (InStr(1, Cell.Value, ",")))))
        Cell.Value = Mid(Cell.Value, 1, InStr(1, Cell.Value, ",") - 1)
    End If
Next Cell

End Sub