Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract specific part of String

Tags:

excel

vba

I am pretty new to VBA, but not programming in general. I am trying to make a macro in VBA that formats the model name of a list of phone names to something manageable. E.g. I want the following name:

P10, 12,9 cm (5.1"), 4 GB, 64 GB, 20 MP

To be formatted as

P10 5.1" 64 GB

I have succeeded in extracting the first two elements of the formatted name using Split and Mid.

This is some of my code for the first two parts:

'First part of format
firstPart = Trim(Split(modelName, ",")(0))
Debug.Print formattedModelName

'Second part of format
openPos = InStr(modelName, "(")
closePos = InStr(modelName, ")")

secondPart = Mid(modelName, openPos + 1, closePos - openPos - 1)

My question is how to go about extracting the 64 GB and not the 4 GB. I tried iterating through all characters and saving the last 5 characters to see if they matched what I wanted. But there must be a better way.

I would appreciate any help, Thank you very much

EDIT

Here is another example of an input and the output as requested: Input:

iPhone iPhone SE, 10,2 cm (4"), 640 x 1136 pixel, 16 GB, 12 MP, iOS 9, Sort, Grå

Expected Output:

iPhone iPhone SE 4" 16 GB

like image 428
Fehrnovic Avatar asked Dec 04 '22 19:12

Fehrnovic


1 Answers

How about using RegEx to extract the values and using the last one. Just add a reference to the library: "Microsoft VBScript Regular Expressions 5.5". Then you can do this..

Option Explicit

Public Function xx()
Dim modelName As String
Dim firstPart As String
Dim Pattern As String
Dim GBString As String
Dim regEx As New RegExp
Dim finalName As String
Dim matches As MatchCollection

Let modelName = "P10, 12,9 cm (5.1""), 4 GB, 64 GB, 20 MP"
firstPart = Trim(Split(modelName, ",")(0))


With regEx
    .Global = True
    .IgnoreCase = True
    .Pattern = "[0-9]+ GB"
End With

Set matches = regEx.Execute(modelName)

If matches.Count > 0 Then
    GBString = matches(matches.Count)
Else
    GBString = "<unknown GB>"
End If

finalName = firstPart + GBString

End Function
like image 159
Auction God Avatar answered Dec 12 '22 03:12

Auction God