One solution is the use of Regular Expressions.
Regular Expression
The following expression may be used: \d+(?=$)
Where this expression captures one or more digits \d+
before the end of the string (?=$)
And the demo can be seen in this link
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.
![Janela Referências](https://i.stack.imgur.com/iJerX.png)
Code
Dim numero As Long
Dim codigo As String, resultado As String
Dim objCorresp As Object, objExpReg As Object
Set objExpReg = CreateObject("VBScript.RegExp")
'Expressão Regular
objExpReg.Pattern = "\d+(?=$)"
objExpReg.Global = True
codigo = "T110A17099"
Set objCorresp = objExpReg.Execute(codigo)
If objCorresp.Count <> 0 Then
For Each c In objCorresp
numero = CLng(c) + 1
codigo = Replace(codigo, c, "")
Next c
End If
resultado = codigo & numero
MsgBox (resultado)
Function Code (UDF)
Function funcao_incrementar(codigo As String) As String
Dim numero As Long
Dim objCorresp As Object, objExpReg As Object
Set objExpReg = CreateObject("VBScript.RegExp")
'Expressão Regular
objExpReg.Pattern = "\d+(?=$)"
objExpReg.Global = True
Set objCorresp = objExpReg.Execute(codigo)
If objCorresp.Count <> 0 Then
For Each c In objCorresp
numero = CLng(c) + 1
codigo = Replace(codigo, c, "")
Next c
End If
funcao_incrementar = codigo & numero
End Function
Testing
Sub teste()
MsgBox (funcao_incrementar("T110A17099"))
End Sub
Can’t separate the numeric part of the string? Then you just have to increment it as a number and re-concatenate.
– jsantos1991
That! In this case we have 5 numerical positions after one letter; in other cases we will have 3 numerical positions after one letter.
– soushinsha
For deduced something of this kind :/ And if you go through the string, inversely until you find the character that is not a number, and then, only increments in that part of the string, I do not know if it is a viable suggestion.
– jsantos1991
That’s exactly what I intend to do! Using the above code I could go back and forth and solve (theoretically). But I see a huge code nestled in. We need something smarter.
– soushinsha