I am new to the vba and trying to solve my situation wherein we recieve multiple mail like below:
we would like to create a database in excel for all the mails which are in my specific folder
Package Summary:
Client: XYZ
Price (USD): 3,000
Time: 1 Week
Project Id: 21312
and some more text......
here we would like to capture the information for Client, Price (USD), Time, Project Id.
Have tried below code which capture the information and stores in excel file.
Sub GetFromOutlook()
Dim OutlookApp As Outlook.Application
Dim OutlookNamespace As Namespace
Dim Folder As MAPIFolder
Dim OutlookMail As Variant
'Dim i As Integer
Set OutlookApp = New Outlook.Application
Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
Set Folder = OutlookNamespace.GetDefaultFolder(olFolderInbox).Folders("Dummy").Folders("New Dummy")
'i = 1
For Each OutlookMail In Folder.Items
Dim sText As String
sText = OutlookMail.Body
Dim Reg1 As RegExp
Dim M1 As MatchCollection
Dim M As Match
Dim vText, vText2, vText3, vText4 As Variant
Dim i As Integer
Set Reg1 = New RegExp
' \s* = invisible spaces
' \d* = match digits
' \w* = match alphanumeric
For i = 1 To 9
With Reg1
Select Case i
Case 1
.Pattern = "(Client[:]([\w-\s]*)\s*)\n"
.Global = False
Case 2
.Pattern = "(([\d]*\,[\d]*))\s*\n"
.Global = False
Case 3
.Pattern = "(Time[:]([\w-\s]*)\s*)\n"
.Global = False
Case 4
.Pattern = "(Project Id[:]([\w-\s]*)\s*)\n"
.Global = False
End Select
End With
If Reg1.Test(sText) Then
Set M1 = Reg1.Execute(sText)
Select Case i
Case 1
For Each M In M1
vText = Trim(M.SubMatches(1))
Next
Case 2
For Each M In M1
vText2 = Trim(M.SubMatches(1))
Next
Case 3
For Each M In M1
vText3 = Trim(M.SubMatches(1))
Next
Case 4
For Each M In M1
vText4 = Trim(M.SubMatches(1))
Next
End Select
End If
Next i
Range("a1000").End(xlUp).Offset(1, 0).Value = vText
Range("b1000").End(xlUp).Offset(1, 0).Value = vText2
Range("c1000").End(xlUp).Offset(1, 0).Value = vText3
Range("d1000").End(xlUp).Offset(1, 0).Value = vText4
Next OutlookMail
Set Folder = Nothing
Set OutlookNamespace = Nothing
Set OutlookApp = Nothing
End Sub
Challenges:
Challenge 1: if the heading Price (USD) changes to Price (GBP) still its storing the value, which should not be. it should only store the value only if the matching text found.
i tried "(Price (USD) [:] ([\d]\,[\d]))\s*\n" however its not working.
Challenge 2: for Project id, value is coming with underscore as well which i am unable to exclude.
Would really appreciate if one can help me solving the above 2 challenge from my code.
or else suggest any better approach for the same.