Extracting specific information from Outlook 2003 to Excel using VBA - vba

So firstly, I'm very new to VBA and due to the number of emails I get that follow a certain template, I'm trying to automate the data collation to save myself from all the cutting and pasting that is currently required. I've looked at some previous questions but due to my very little knowledge, the answers aren't specific enough for me to understand.
Each one of these emails is from a particular email address and has a standard format as shown below:
"
dd/mm/yyyy hr.min.sec
xxx xxxxxxx xxxxxxxxxxxxxxxxx xxxx xxxxx "
I would like to export or copy this information to an excel 2003 worksheet so that each separate piece of information is in a new column of a single row, where each email is a new row.
I would like the macro to be able to search through my received emails in a particular folder (as I've already set up some rules in outlook relating to this email address), copy the information from each email matching the template and paste it into a single excel worksheet. Then each time I get a new email, the information will be added to the bottom of the table thats been created.
Hopefully that all makes sense, please let me know if you need anymore information.
Thanks in advance.

I did something exactly like this recently, except that I had it entered into an access database instead of an excel sheet, but the idea is the same. For some reason, I was having trouble getting it to run with rules, but I anyways found that I could control it better from a manually run macro. So use a rule to put everything into a folder, and make an AlreadyProcessed subfolder under that. Here is some code to start from:
Sub process()
Dim i As Integer, folder As Object, item As Object
With Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Folders("YourFolderName")
For Each item In .Items
processMail item
item.Move .Folders("AlreadyProcessed")
Next
End With
End Sub
Sub processMail(item As Outlook.MailItem)
Dim bitsOfInformation() As String
bitsOfInformation = Split(item.Body, " ")
'Use this information to make an Excel file
End Sub
Making Excel files from VBA are very easy - just read up on opening excel and making new documents from other Office program VBAs - you're looking for Excel.Application. You can even record a macro in Excel, filling the information manually, and basically copy the code into Outlook and replace the hard-coded information with variables. But if you're going to be running this on thousands of e-mails, be warned that recorded macros (that use selection objects) are inefficient.

Start with the following code:
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Set Items = GetItems(GetNS(GetOutlookApp), olFolderInbox)
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error GoTo ErrorHandler
Dim msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set msg = item
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
Function GetItems(olNS As Outlook.NameSpace, folder As OlDefaultFolders) As Outlook.Items
Set GetItems = olNS.GetDefaultFolder(folder).Items
End Function
Function GetNS(ByRef app As Outlook.Application) As Outlook.NameSpace
Set GetNS = app.GetNamespace("MAPI")
End Function
Function GetOutlookApp() As Outlook.Application
Set GetOutlookApp = Outlook.Application
End Function
This sets an event listener on your default Inbox. Whenever an email message is received, the code inside the If TypeName statement will be executed. Now it's simply a matter of what code you want to run.
You can check the sender using the .SenderName or .SenderEmailAddress properties to make sure it's the right sender.
If you provide more specific information, I can amend the code.

Related

VBA to add username upon row creation

I currently have a scenario that has several users entering data rows to an Excel table. There is no shared workbook setup involved so only one user will have the document open at anyone time. Is there a VBA method I can use to capture the name of the user that currently has the document open and insert it each time a line is added to the table? Thereby giving an author for each row.
you can add the following code in the code pane of the relevant worksheet
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Columns("A:N"), Target) Is Nothing Then Cells(Target.Row, "O").Value = Environ$("Username")
End Sub
of course you can fine-tune the If clause that have username inserted in column "O"
The following code will grab the name of the user:
Application.UserName
I find on my work computer at least:
Environ$("Username"‌​) gives Admin
Application.UserName gives IT
Now, I could change my Application.UserName to my name - easy enough to do with a little knowledge, but I find a lot of office staff don't have that little knowledge....
Outlook on the other hand is often set to the specific user, so when Excel first opens and stored in a global variable:
Sub Test()
Dim olApp As Object
Set olApp = CreateObject("Outlook.Application")
MsgBox olApp.session.currentuser
End Sub

Why was I able to execute a method without qualifying the object name?

I was automating an Outlook email from excel today when I noticed I forgot a line but somehow it still worked and I didn't get a compile error. Is there such as thing as a default library object?
Sub sendmail()
Dim olmsg As Outlook.MailItem
'This works
Set olmsg = Outlook.CreateItem(olMailItem)
'What it should be
Set olmsg = Outlook.Application.CreateItem
End Sub
When working in Outlook, it automatically recognizes Outlook types.
Similar to how Excel will recognize keywords such as ActiveSheet and ActiveCell without first expressing Excel.Application.
It is good practice to use the longhand expression, incase you ever need to port a similar code to Excel for working in Outlook, and because VBA does not handle overflows well.

Macro works on one computer but not the other

Fair warning - the code is not my own, so any ideas will be welcomed on how to change it.
Public Sub ChangeMeeting()
Dim oRequest As MeetingItem
Dim oAppt As AppointmentItem
Set oRequest = Application.ActiveExplorer.Selection.Item(1)
If oRequest.MessageClass = "IPM.Schedule.Meeting.Request" Then
Set oAppt = oRequest.GetAssociatedAppointment(True)
' use this to autoaccept
Dim oResponse
Set oResponse = oAppt.Respond(olMeetingAccepted, True)
oResponse.Send
' set fields on the appt.
With oAppt
' .Categories = "Slipstick"
.BusyStatus = olFree
.Save ' use .Display if you want to see the appt. and set the reminder yourself
End With
End If
'delete the request from the inbox
oRequest.Delete
End Sub
This one's interesting. On my computer, it works just fine. However, on the other one it can be clicked on and clicked on, and nothing will happen. No errors, no popups, no nothing. So, I know that the code works, but is there any reason (rights?) that the exact same code would work on one and not the other?
First of all, make sure that VBA macros are allowed to run. Is the VBA macro run in Outlook at all? Did you try to debug it?
Do you get any errors in the code on another machines?
I'd suggest starting from breaking the chain of property and method calls and declaring them on separate lines of code. Thus, you will be able to find what property or method fails.
The code is based on the selected item in the Explorer:
Application.ActiveExplorer.Selection.Item(1)
Is the selection not empty all the time?
If oRequest.MessageClass = "IPM.Schedule.Meeting.Request"
Does the selection contains the first item with the specified message class?
In general, VBA macros are not designed for distributing on multiple PCs. If you need to get a solution working on multiple machines you need to develop an add-in instead. See Walkthrough: Creating Your First VSTO Add-In for Outlook .
Finally, you may find the Getting Started with VBA in Outlook 2010 article helpful.

Outlook Get Other Emails in Email Thread--UniqueBody

I am using VBA to format all outbound email messages in a certain way before sending. For example, I want to remove the first column from all tables which are embedded in the email. I use the following code:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim wd As Word.Document
Set wd = ActiveInspector.WordEditor
Dim tb As Word.Table
For Each tb In wd.Tables
tb.Columns(1).Delete
Next tb
End Sub
The above code works perfectly. However, the problem is that I only want to format my email text. Often, I will be responding to or forwarding someone else's email, which means that the text of the previous email will be in the same Inspector window. I don't want to format the text/images/etc. of the previous emails in the thread. How can this be achieved?
I know that each email within a thread--although they're all in the same window--is an individual unit. I know this because when reading an email which is part of a thread, as you move the mouse, you will see
on the right side of the screen, indicating where the next part of the thread is. When composing a new email (reply or forward) which is part of the thread, the above buttons are not shown, but you will still see a blue horizontal line separating the different parts of the thread from each other.
I was thinking that maybe I can search for the first occurrence of the line in the email, and only apply the formatting up until that point. However, it appears that the line isn't really text or any regular formatting which is searchable in the normal sense. In fact, if you copy the email text (before sending), and then paste into Word, the line disappears.
Any suggestions?
Thanks!
Update
My question has nothing to do with the "conversation view" found in versions 2010 and later.
Outlook 2010 allows you to view the other emails in the thread in one group. What I want, however, is to be able to loop through (via code) the emails in the thread within the same email. So, if there was an email "a", and then a reply, "b", and then another reply, "c", c will also contain b beneath it, and then a beneath that, all within the same email. In pseudo-code, I would want the following:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim wd As Word.Document
Dim smail as SubEmail
Dim tb As Word.Table
Set wd = ActiveInspector.WordEditor
For Each smail in wd
For Each tb In wd.Tables
tb.Columns(1).Delete
Next tb
Exit For
Next smail
End Sub
Update
I found a similar feature in Exchange Web Services, called UniqueBody. See here. That's exactly what I'm looking for, just not with Exchange.
Why not just look for "From:" chr(13) "Sent:" ? Outlook is going to put those tags in any email regardless of where it came from.
Assume that the entire body of emails a, b, c in your example above are in sBody:
Sub GetFirstThread()
Dim olItem As Outlook.MailItem
Dim sText As String
Set olItem = ActiveExplorer.Selection.Item(1)
sBody = olItem.Body
i=1
While i < Len(sBody)
If Asc(Mid(sBody, i, 1)) = 13 Then 'Look for From:
If Mid(sBody, i + 1, 5) = "From:" Then
'we found the start of email b
nPosEb = i
End If
End If
i=i+1
Wend
'...do something with nPosEb
End Sub

Creating VBA macro to save email copy

I use Outlook (MS Exchange) and have an individual as well as two group inboxes (I'm working logged in with the individual profile through which I also have access to the group inboxes).
When I send an email, I chose either my individual or one of the two group email addresses in the From field. When the email is sent, I want a copy saved in the inbox of myIndividualMailbox, groupAMailbox, or groupBMailbox depending on which From email address I used.
Example: If I send an email From groupA#myCompany.com, I want a copy of the email saved in the inbox of the groupAMailbox (and not in my individual inbox).
I have understood that this is not possible by setting up a rule in Outlook but that it could be done with a VBA macro. I don't now how to write the VBA macro and don't know if this is a just a short script or more complicated. In fact I have never written a macro in Outlook so I don't even know how to begin. Can anyone show how to do this?
I started looking for a solution with this question: Outlook send-rule that filter on the 'From' field
I made this for you as far as I can tell, it works. You should put this in the Microsoft Outlook Objects - ThisOutlookSession Module.
Note that the myolApp_ItemSend event will never trigger unless you run enableEvents first. And you will need to make sure it is enabled every time you close an re-open Outlook. This will take some customization, but it should give you the general idea.
Option Explicit
Public WithEvents myolApp As Outlook.Application
Sub enableEvents()
Set myolApp = Outlook.Application
End Sub
Private Sub myolApp_ItemSend(ByVal item As Object, Cancel As Boolean)
Dim items As MailItem
Dim copyFolder As Outlook.Folder
Dim sentWith As String
'Identify sender address
If item.Sender Is Nothing Then
sentWith = item.SendUsingAccount.SmtpAddress
Else
sentWith = item.Sender.Address
End If
'Determin copy folder based on sendAddress
Select Case sentWith
Case "groupA#myCompany.com"
'get groupAMailbox's inbox
Set copyFolder = Application.GetNamespace("MAPI").folders("groupAMailbox").folders("Inbox")
Case "myE-mailAddress"
'get My inbox
Set copyFolder = Application.GetNamespace("MAPI").folders("myE-mailAddress").folders("Inbox")
End Select
'copy the Item
Dim copy As Object
Set copy = item.copy
'move copy to folder
copy.Move copyFolder
End Sub
EDIT: It looks like they've actually built the event functionality into the Application object for Outlook directly now, but it from testing you still have to do what I outlined above.
Outlook stores all sent items in default sent items folders. however you can apply a patch to save sent items in its own folder.
http://support.microsoft.com/kb/2181579