Solution
You can use Regex as a VBA function to validate this.
Regex
Enable Regex in Excel
- Regex needs to be enabled, Enable the Developer mode
- In the 'Developer' tab, click 'Visual Basic' and the VBA window will open.
- Go to 'Tools' -> 'References...' and a window will open.
- Search for 'Microsoft Vbscript Regular Expressions 5.5', as in the image below. And enable this option.
Expression
The expression to find cell phone numbers is as follows: ^[6|7|8|9](?:\d{7}|\d{3}\s*-\s*\d{4})$
Where you find numbers that start with 6,7,8 and 9 and have 7 digits after starting with these numbers or 3 digits - (hyphen) 4 digits.
Note: In São Paulo the numbers that start with 5 are hybrid between fixed and mobile telephony. (Telek). Therefore, there is no clear rule for numbers starting with 5.
The demo of Regex101 can be seen and the Debuggex also.
UDF (User Defined Function) in Excel VBA
Code
First insert this function into a module.
Function ValidarCelular(Myrange As Range) As String
On Error GoTo ErrHandler:
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim strOutput As String
strPattern = "^[6|7|8|9](?:\d{7}|\d{3}-\d{4})$"
If strPattern <> "" Then
strInput = Trim(Myrange.Value)
strReplace = "9" & strInput
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.test(strInput) Then
ValidarCelular = regEx.Replace(strInput, strReplace)
Else
ValidarCelular = Myrange.Value
End If
End If
Exit Function
ErrHandler:
' Tratamento de Erro
ValidarCelular= CVErr(xlErrNA)
On Error GoTo 0
End Function
Upshot
The test was done with validation data in column A and inserting the function =ValidarCelular(A1)
in column B.
Explanation Code
- Creates the function
ValidarCelular
with MyRange
as an input variable, i.e., an input variable cell.
- Adds the Regex pattern in
strPattern
- The Regex entry is
strInput
, using the function Trim()
to remove blanks at start and end.
- The
strReplace
is the string that will replace what is in the cell if it is a cell number. Adding the number 9 in front with "9" & strInput
How so "not working"? What exactly goes wrong? You should report the error that is happening.
– Gabriel