I need some help with VBA to count emails from 7 different subfolders of Outlook.
The result must show the number of emails in these subfolders and the date of the last email.
This subfolder is added as an extension to my Outlook only for processing data and is not my actual Outlook email. It has further subfolders inside of it which needs to be counted.
I hope someone can help me with this.
Thanks in advance
It seems you need to iterate over all folder recursively because the nesting level is unknown. The following code iterates over all folders in Outlook recursively:
sub ProcessFolders(Folders)
for each folder in Folders
if Folder.DefaultItemType = olMailItem Then
Debug.Print "--------- " & folder.Name
End If
ProcessFolders(folder.Folders)
next
end sub
Here is how you could invoke it:
ProcessFolders(Application.Session.Folders)
The result must show the number of emails in these subfolders and the date of the last email.
The Items.Count property returns a long indicating the count of objects in the specified collection of folder. For example:
folderInstance.Items.Count
To find the date of last email (I suppose the last received one) you need to sort the collection using the Items.Sort method which orts the collection of items by the specified property. The index for the collection is reset to 1 upon completion of this method.
Set myItems = myFolder.Items
myItems.Sort "[ReceivedTime]", True
MsgBox myItems(1).ReceivedTime
Related
I have a userform with a treeview control MSComctlLib.TreeView. It is used to save files that are dragged on top of it to the drive. My problem is that whenever an email has multiple attachment and one is dragged over, there is no apparent way to tell which one specific attachment out of multiple is selected.
Code below includes an event fired when the file is dragged to the TreeView and then calls a sub based on the DataObject format. When the attachment is dragged, this code parses all of the attachments in the currently selected email (after filtering out embedded images). The ordering of attachments does not change based on which attachment is selected and I could not find a PropertyAccessor property that may be helpful.
Private Sub treeView_OLEDragDrop(Data As MSComctlLib.DataObject, Effect As Long, Button As Integer, Shift As Integer, x As Single, y As Single)
Select Case True
Case Data.GetFormat(13): 'process Email
Case Data.GetFormat(15): 'process files
Case Else: processAttachments
End Select
End Sub
Private Sub processAttachments()
Dim outlookApp As Object: Set outlookApp = CreateObject("Outlook.Application")
Dim selection As Object: Set selection = outlookApp.activeexplorer.selection
Dim email As Object
Dim attachment As Object
For Each email In selection
For Each attachment In email.Attachments
If Not attachment.PropertyAccessor. _
GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003") = 4 _
Then ' filters out embedded images
Debug.Print attachment.DisplayName
End If
Next
Next
End Sub
Is there a method to determine which one of the email attachments is currently selected or is currently being dragged over?
The best what you could do is to track the currently selected attachment in Outlook, so if the drag and drop operation is made you could quickly get the currently selected attachment. Or just use the AttachmentSelection property as explained below to get the selected attachments in Outlook.
The Explorer.AttachmentSelectionChange event is fired when the user selects a different or additional attachment in the active explorer programmatically or by interacting with the user interface.
The Inspector.AttachmentSelectionChange event is fired when the user selects a different or additional attachment of an item in the active inspector programmatically or by interacting with the user interface.
To get the selected attachments you need to use the Explorer.AttachmentSelection or Inspector.AttachmentSelection property which returns an AttachmentSelection object consisting of one or more attachments that are selected in the explorer or inspector respectively.
The AttachmentSelection object contains a read-only collection of attachments that are selected in an item that is in the active inspector or the active explorer.
I hope you can help me. I am new to Outlook 2010 VBA, but need a macro to :-
Save a group of highlighted e-mails :-
a) As .msg files;
b) In a given folder;
c) Where the name of each is the attachment name.
To give you an example, say there are 20 e-mails in my sent items folder, I want to highlight 10 of them and run this macro, winding-up with 10 flat files in a given folder which bear the name of the attachment for each e-mail.
Every e-mail subjected to this macro will have just one attachment, so to be crystal-clear, if we have an e-mail with a subject line "Random Text goes here doesn't matter what", and an attachment "GO.XLSX", I want the extracted file to be called GO.msg and, to confirm, this is Outlook 2010 I am running.
I have looked through loads of VBA sites and macro snippets, but I am getting nowhere =[
Not sure if I understand your problem, but here is a quick example:
Sub QuickExample()
For Each Item In Application.ActiveExplorer.Selection
If Item.Attachments.Count > 0 Then
Debug.Print Item.Attachments(1).DisplayName
End If
Next
End Sub
I am wondering if there is a way using VBA/Outlook to look through a number of personal folders (all added to Outlook and called personal folders) and copy the contents of the inboxes (the folder will always be called Inbox) to a single PST/inbox/folder. The number of personal folders would vary depending upon the email search completed (GVault).
Personal Folder - Inbox,
Personal Folder - Inbox,
Personal Folder - inbox,
Final Personal Folder - Inbox
The aim is to give the user one PST with all the emails in.
This is part of an attempt to streamline our email archive search process which creates a folder + PST for each email address found in the search (good old Google....) It is obviously a nightmare combining them all into one PST which we can then give to a user. It is possible (using Outlook) to manually combine each PST with a master PST but this is far from automating the process + there could be a large amount of separate email addresses.
The original problem was taking all the PSTs and getting them into Outlook, this has been solved but the format is as described above (seperate PSTs all added).
Any help would be greatly appreciated as I cant get past this final hurdle, there are scripts that do manipulate PSTs in Outlook, they just dont do this.
Thanks
Dan
Below code will loop your outlook attached PST files copying files in a folder called 'Inbox' (any case) to the PST callled 'Master PST'
Included very trivial error checking <-- free to improve
'include reference to Microsoft Outlook XX.0 Object Library
Public Sub copyInbox()
Dim ns As Outlook.Namespace
On Error GoTo hell
Dim sourceFolder As Outlook.MAPIFolder
Dim copyToFolder As Outlook.MAPIFolder
Dim subfolder As Outlook.MAPIFolder
Dim objItem As Outlook.MailItem
Dim objItemCopy As Outlook.MailItem
Set ns = Application.GetNamespace("MAPI")
Set copyToFolder = ns.Folders("MASTER PST").Folders("Inbox")
'Personal folder called 'MASTER PST' with inbox subfolder must exist
For Each sourceFolder In ns.Folders
For Each subfolder In sourceFolder.Folders
If Trim(UCase(subfolder.Name)) = "INBOX" Then
For Each objItem In subfolder.Items
'modified below to use copy as per MSDN
'https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/mailitem-copy-method-outlook
Set objItemCopy = objItem.Copy
objItemCopy.Move copyToFolder
Next
End If
'copy items in subfolders in inbox can be added here
Next
Next
Exit Sub:
hell:
MsgBox Err.Description, vbExclamation, Err.Source
End Sub
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.
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