在VBA中如何分离不规则数量的分隔符和匹配string

我有一列电话号码,如01-665-678744,或02-0512-6789-4567,类似的东西。 假设这个列是在列D中。我想用' – '分割数字,但只有列的第一部分在它的左边:列C,剩下的仍然保存在列d中。 所以在运行代码之后,下面是效果:

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

我觉得我应该使用数组或分裂,也许UBound,但无法创build它。
有谁能够帮助我?
谢谢。

试试这个代码:

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 

既然你想覆盖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 

依靠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