如何在VBA中用不规则数量的分隔符分隔字符串并加以解调

时间:2016-01-14 16:32:35

标签: excel vba excel-vba

我有一列电话号码,如01-665-678744,或02-0512-6789-4567,就像那样。假设此列位于D列中。我想将数字与' - '分开,但只是左侧列中的第一部分:C列,剩下的仍然存储在专栏d。所以在运行代码之后,下面就会产生影响:

| 01 | 665-678744 |
| 02 | 0512-6789-4567 |

我觉得我应该在数组或分裂中使用,也许是UBound,但是我无法创建它 有人能帮帮我吗? 谢谢。

3 个答案:

答案 0 :(得分:1)

试试这段代码:

Sub test()
 Dim i As Long, Rng As Range, Cnt As Long
 Dim VV As Variant, V1() As String, Sp() As String

 Set Rng = Range("d1:d5") ' change this as you need but don't use column "A"
 Cnt = Rng.Rows.Count
 ReDim V1(1 To Cnt, 1 To 2)
 VV = Rng.Value

  For i = 1 To Cnt
    Sp = Split(VV(i, 1), "-")
    V1(i, 1) = Sp(0)
    V1(i, 2) = Right(VV(i, 1), Len(VV(i, 1)) - Len(Sp(0)) - 1)
  Next

  Range(Rng, Rng.Offset(, -1)) = V1

End Sub

如果您的范围可以包含空单元格或没有" - "的任何值,则可以使用此代码:

Sub telf()
 Dim i As Long, Rng As Range, Cnt As Long
 Dim VV As Variant, V1() As String, Sp() As String

 Set Rng = Range("d1:d10") ' change this as you need but don't use column "A"
 Cnt = Rng.Rows.Count
 ReDim V1(1 To Cnt, 1 To 2)
 VV = Rng.Value
 On Error Resume Next
  For i = 1 To Cnt
    Sp = Split(VV(i, 1), "-")
    If UBound(Sp) = 0 Then
     V1(i, 2) = VV(i, 1)
    Else
     V1(i, 1) = Sp(0)
     V1(i, 2) = Right(VV(i, 1), Len(VV(i, 1)) - Len(Sp(0)) - 1)
    End If
  Next

  Range(Rng, Rng.Offset(, -1)) = V1
 On Error GoTo 0
End Sub

答案 1 :(得分:0)

由于您要覆盖D列,因此您需要VBA(您要求的)。您可以使用公式轻松完成此操作(如果不是更多),您只需要一个辅助列。

这是您想要获得的内容的一个子目录:

Sub test()
Dim lastRow&
Dim firstPart$, secondPart$
Dim rng As Range, cel As Range

lastRow = Cells(Rows.Count, 4).End(xlUp).Row
Set rng = Range(Cells(1, 4), Cells(lastRow, 4))

For Each cel In rng
    firstPart = Left(cel.Value, 2)
    secondPart = Mid(cel.Value, 4, Len(cel.Value))
    Debug.Print firstPart & ", " & secondPart
    cel.Offset(0, -1).Value = "'" & firstPart
    cel.Value = secondPart
Next cel

End Sub

答案 2 :(得分:0)

在J30上执行操作,您可以为每个单元格使用循环。

Sub test()

    Dim strSplitOne() As String

    strSplitOne = Split(Range("J30").Value, "-")

    Range("J30").Offset(0, 1).Value = "'" & strSplitOne(0)

    strSplitOne(0) = ""

    Range("J30").Offset(0, 2).Value = WorksheetFunction.Substitute(Join(strSplitOne, "-"), "-", "", 1)


End Sub