如何使用VBA Excel过滤正确的电话号码

时间:2015-02-23 08:30:47

标签: excel-vba vba excel

我在一列中有很多电话号码(印度格式),其中包含未使用的符号。我试图通过使用VBA用户定义函数删除它们,以便phone_number只包含10位数。 RightNow我是通过逐个替换手动完成的。这些是我的phone_number: -

+91-9999998989
+-919999999999
-919999999999
-91+9999999999
91-9999999999
091-9999999999
9109999999999
0119999999999
011-9999999999
011 9999999999
987 7845789
7894(784752
7842)748592
7844785621and7854789562
987-1457956
987457812579562147853

所以我的输出是: -

9999998989
9999999999
9999999999
9999999999
9999999999
9999999999
9999999999
9999999999
9999999999
9999999999
9877845789
7894784752
7842748592
7844785621and7854789562 // this is take first number
9871457956
987457812579562147853 // this will take first 10 digit

我想,我需要使用正则表达式。请帮我创建功能。你的帮助将会对我很感激。

1 个答案:

答案 0 :(得分:1)

以下代码正在考虑您的号码在A栏中,并删除了所有非数字字符。

Sub OnlyNumber()
Dim s As String
Dim ReturnVal As String
Dim i As Integer
Dim lastRow As Long

ReturnVal = ""
lastRow = Range("A" & Rows.Count).End(xlUp).Row

    For c = 1 To lastRow
        s = Range("A" & c).Value
            For i = 1 To Len(s)
                If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then
                ReturnVal = ReturnVal + Mid(s, i, 1)
                End If
            Next i
        If Len(ReturnVal) > 10 And Len(ReturnVal) <= 14 Then
            Range("A" & c).Value = Right(ReturnVal, 10)
            ElseIf Len(ReturnVal) > 14 Then
                Range("A" & c).Value = Left(ReturnVal, 10)
                ElseIf Len(ReturnVal) = 10 Then
                    Range("A" & c).Value = ReturnVal
                    Else
                    MsgBox ("Not defined number structure")
        End If
        ReturnVal = ""
    Next c
End Sub