Reference inbox of a different account - excel

I am looking for a way to pull down the information of a different Outlook account into an Excel spreadsheet.
The below code works only for my personal inbox:
Sub psinbox()
Dim olNs As Outlook.Namespace
Dim oltaskfolder As Outlook.MAPIFolder
Dim oltask As Outlook.TaskItem
Dim olitems As Outlook.Items
Dim xlapp As Excel.Application
Dim xlWB As Excel.Workbook
Dim x As Long
Dim arrheaders As Variant
Set olNs = GetNamespace("MAPI")
Set oltaskfolder = olNs.GetDefaultFolder(olFolderInbox)
Set olitems = oltaskfolder.Items
Set xlapp = CreateObject("Excel.Application")
xlapp.Visible = True
Set xlWB = xlapp.Workbooks.Add
x = 2
arrheaders = Array("Date Created", "Date Recieved", "Subject", "Sender",
"Senders Email", "CC", "Sender's Email Type", "MSG Size", "Unread?")
On Error Resume Next
xlWB.Worksheets(1).Range("A1").Resize(1, UBound(arrheaders)).Value = ""
Do
With xlWB.Worksheets(1)
If Not (olitems(x).Subject = "" And olitems(x).CreationTime = "") Then
.Range("A1").Resize(1, UBound(arrheaders) + 1) = arrheaders
.Cells(x, 1).Value = olitems(x).CreationTime
.Cells(x, 2).Value = olitems(x).recievedtime
.Cells(x, 3).Value = olitems(x).Subject
.Cells(x, 4).Value = olitems(x).SenderName
.Cells(x, 6).Value = olitems(x).CC
.Cells(x, 7).Value = olitems(x).SenderEmailType ' this is either internal or external server
.Cells(x, 8).Value = Format((olitems(x).Size / 1024) / 1024, "#,##0.00") & " MB"
.Cells(x, 9).Value = olitems(x).UnRead
x = x + 1
End If
End With
Loop Until x >= olitems.Count + 1
Set olNs = Nothing
Set oltaskfolder = Nothing
Set olitems = Nothing
Set xlapp = Nothing
Set xlWB = Nothing
End Sub
I want to record how many received emails are unread.
The closest I found was here Count Read and Unread Emails date wise for shared mailbox , which mentioned that would need to Set c = b.Folders("Name of shared mailbox"), however this appears to be for different folders inside the same mail account. What I am after though is access to two different accounts which outlook has access to?
Edit:
Having tried Niton's example, I am having an issue with the below.
If objOwner.Resolved Then
Set oltaskfolder = olNs.GetSharedDefaultFolder(objOwner,
olFolderInbox).Folders("admin")
Set olitems = oltaskfolder.Items
End If
I have tried to use the user name of the shared inbox, the email address, and the name of the email account, but all bring up the following error.

The answer it seems was to remove a section which caused complications.
If objOwner.Resolved Then
Set oltaskfolder = olNs.GetSharedDefaultFolder(objOwner,
olFolderInbox)
Set olitems = oltaskfolder.Items
End If
Removing .Folders("admin") fixed the error that was coming up and solved the issue. It then gave me the information about the inbox exactly as required.
Edit:
Side note which I just found out, if you do want to have a sub folder in a shared mail box, just add the .Folders("mailbox") next to the olFolderInbox instead like below.
If objOwner.Resolved Then
Set oltaskfolder = olNs.GetSharedDefaultFolder(objOwner,
olFolderInbox).Folders("mailbox")
Set olitems = oltaskfolder.Items
End If
The previous pages did not work adding it next to CreateRecipient ??

Related

How to Convert my VBA process to run in MAC?

I have an excel macro that works perfect in windows (email text extraction), but when I run it in my mac it gives me the error missing the library Microsoft Outlook 16.0 Object Library.
I was thinking in late binding (I tried but I wasn't able to fix it)
Can you pls help me to fix my code in order to run it in my mac? thanks in advance.
Code Below:
Sub DetailExtraction() 'MacVersion
On Error GoTo ErrHandler
Application.ScreenUpdating = False
' SET Outlook APPLICATION OBJECT.
Dim objOutlook As Object
Set objOutlook = CreateObject("Outlook.Application")
' CREATE AND SET A NameSpace OBJECT.
Dim objNSpace As Object
' THE GetNameSpace() METHOD WILL REPRESENT A SPECIFIED NAMESPACE.
Set objNSpace = objOutlook.GetNamespace("MAPI")
' CREATE A FOLDER OBJECT.
Dim myFolder As Object
Set myFolder = objNSpace.GetDefaultFolder(olFolderInbox)
Dim Item As Object
Dim iRows, iCols As Integer
iRows = 2
' LOOP THROUGH EACH ITEMS IN THE FOLDER.
'For Each objItem In myFolder.Items
' LOOP THROUGH EACH ITEMS IN THE SELECTION.
For Each objItem In ActiveExplorer.Selection
If objItem.Class = olMail Then
Dim objMail As Outlook.MailItem ' PROBLEM IS IN THIS LINE
Set objMail = objItem
Cells(iRows, 1) = objMail.SenderEmailAddress
Cells(iRows, 2) = objMail.To
Cells(iRows, 3) = objMail.Subject
Cells(iRows, 4) = objMail.ReceivedTime
Cells(iRows, 6) = objMail.Body
Cells(iRows, 6).WrapText = False
'MsgBox Prompt:=objMail.Body
End If
'WRAP UP FILE OFF
' Cells*i.WrapText = False
' SHOW OTHER PROPERTIES, IF YOU WISH.
'Cells(iRows, 6) = objMail.Body
'Cells(iRows, 5) = objMail.CC
'Cells(iRows, 6) = objMail.BCC
'Cells(iRows, 4) = objMail.Recipients(1)
iRows = iRows + 1
Next
Set objMail = Nothing
' RELEASE.
Set objOutlook = Nothing
Set objNSpace = Nothing
Set myFolder = Nothing
ErrHandler:
Debug.Print Err.Description
Application.ScreenUpdating = True
MsgBox "Environments Details Extracted from the Selected Emails (" & iRows - 2 & ")"
End Sub

Excel VBA code working except one computer - Error 91

I have an Excel VBA sub that is used to search for contact details in Outlook.
The function is working on many computer except one that is the primary user of this function, on which it produces the error:
Error 91: Object variable or With block variable not set
Can someone help me please?
'Function to import Outlook contacts according to their client code
Sub ExportOutlookAddressBook()
Application.ScreenUpdating = False
Dim olApp As Outlook.Application
Dim olNS As Outlook.Namespace
Dim olAL As Outlook.AddressList
Dim olEntry As Outlook.AddressEntry
Dim CodeClient As String
Dim RCompanyName As String
Dim i As Integer
Dim AccountCount As Integer
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
CodeClient = 0
RCompanyName = 0
i = 0
AccountCount = olNS.Accounts.Count
Range("AA6:AF10").ClearContents
For i = 1 To AccountCount
Set olAL = olNS.AddressLists(i) 'Change name if different contacts list name
Set olEntry = olAL.AddressEntries(1)
ActiveWorkbook.ActiveSheet.Range("K6").Select
CodeClient = ActiveCell.Value
ActiveWorkbook.ActiveSheet.Range("AA6").Select
For Each olEntry In olAL.AddressEntries
' your looping code here
RCompanyName = Left(Right(olEntry.GetContact.CompanyName, 7), 6)
If RCompanyName = CodeClient Then
ActiveCell.Value = olEntry.GetContact.FullName
ActiveCell.Offset(0, 1).Value = olEntry.GetContact.BusinessTelephoneNumber 'business phone number
ActiveCell.Offset(0, 2).Value = olEntry.Address 'email address
ActiveCell.Offset(0, 3).Value = olEntry.GetContact.CompanyName
ActiveCell.Offset(0, 4).Value = olEntry.GetContact.BusinessAddress
ActiveCell.Offset(1, 0).Select
End If
Next olEntry
Next i
Set olApp = Nothing
Set olNS = Nothing
Set olAL = Nothing
Application.ScreenUpdating = True
ActiveWorkbook.ActiveSheet.Range("K7").Select
End Sub
Try this.
Besides adding the If Nothing...'s, I tidied some of the other repetative code.
Option Explicit 'this line is recommended at the very top of every module.
'Function to import Outlook contacts according to their client code
Sub ExportOutlookAddressBook()
Dim olApp As Outlook.Application, olNS As Outlook.Namespace, olAL As Outlook.AddressList
Dim olEntry As Outlook.AddressEntry, CodeClient As String, RCompanyName As String, i As Long
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
Application.ScreenUpdating = False
Range("AA6:AF10").ClearContents
For i = 1 To olNS.Accounts.Count
Set olAL = olNS.AddressLists(i) 'Change name if different contacts list name
Set olEntry = olAL.AddressEntries(1)
CodeClient = ActiveWorkbook.ActiveSheet.Range("K6")
ActiveWorkbook.ActiveSheet.Range("AA6").Select
For Each olEntry In olAL.AddressEntries
' your looping code here
RCompanyName = Left(Right(olEntry.GetContact.CompanyName, 7), 6)
If RCompanyName = CodeClient Then
With ActiveCell
.Value = olEntry.GetContact.FullName
.Offset(0, 1) = olEntry.GetContact.BusinessTelephoneNumber 'business phone number
.Offset(0, 2) = olEntry.Address 'email address
If Not olEntry.GetContact Is Nothing Then
If Not olEntry.GetContact.CompanyName Is Nothing Then
.Offset(0, 3) = olEntry.GetContact.CompanyName
End If
If Not olEntry.GetContact.BusinessAddress Is Nothing Then
.Offset(0, 4) = olEntry.GetContact.BusinessAddress
End If
End If
.Offset(1, 0).Select
End With
End If
Next olEntry
Next i
Set olApp = Nothing
Set olNS = Nothing
Set olAL = Nothing
Application.ScreenUpdating = True
ActiveWorkbook.ActiveSheet.Range("K7").Select
End Sub

Use Excel to make appointment in All Public Folders Calendar in 2013 MS Exchange

My code works fine in the default calendar but I am unable to get it to made an appointment in the AllPublicFolders Calendar. I am unable to call the function GetPublicFolder because I am new using VBA. Any help would be greatly appreciated.
Here is my code with "Big Store A Calendar in the all public folders:
Option Explicit
Sub RegisterAppointmentList()
' adds a list of appointments to the Calendar in Outlook
Dim olApp As Outlook.Application
Dim olAppItem As Outlook.AppointmentItem
Dim r As Long
On Error Resume Next
'Worksheets("Schedule").Activate
Worksheets("Appt").Activate
Set olApp = GetObject("", "Outlook.Application")
On Error GoTo 0
If olApp Is Nothing Then
On Error Resume Next
Set olApp = CreateObject("Outlook.Application")
On Error GoTo 0
If olApp Is Nothing Then
MsgBox "Outlook is not available!"
Exit Sub
End If
End If
'r = 6 ' first row with appointment data in the active worksheet
r = 2 ' first row with appointment data in the active worksheet
Dim mysub, myStart, myEnd
While Len(Cells(r, 2).Text) <> 0
mysub = Cells(r, 2) & ", " & Cells(r, 3)
myStart = DateValue(Cells(r, 5).Value) + Cells(r, 6).Value
myEnd = DateValue(Cells(r, 7).Value) + Cells(r, 8).Value
'DeleteTestAppointments mysub, myStart, myEnd
Set olAppItem = olApp.CreateItem(olAppointmentItem) ' creates a new appointment
With olAppItem
' set default appointment values
.Location = Cells(r, 2)
.Body = Cells(r, 3).Value
.ReminderSet = False
.BusyStatus = olFree
'.RequiredAttendees = "johndoe#microsoft.com"
On Error Resume Next
.Start = myStart
.End = myEnd
.Subject = Cells(r, 1)
.Location = Cells(r, 2)
.Body = Cells(r, 3).Value
'.ReminderSet = True
'.BusyStatus = olBusy
.Categories = Cells(r, 4).Value
On Error GoTo 0
.Save ' saves the new appointment to the default folder
End With
r = r + 1
Wend
Set olAppItem = Nothing
Set olApp = Nothing
' Print the Appt Sheet
Sheets("Sheet1").PrintOut
MsgBox "The Appt Sheet Printed and the Appt was entered in your default calendar on May 31st!"
End Sub
‘-------------------------I Need to get correct Public folder for the Exchange calendar -------------
‘I am using VBA for excel workbooks and need to create appointments in 2 public folder shared calendars
‘I need to get code like the code below to create appointments in the shared public calendar – ‘
‘I determine which calendar for the appointment using a workbook cell which is a list box of the 2 calendar names –
‘ Big Store A Calendar or Big Store B Calendar
' GetFolder - Gets a Public folder based on a string path - e.g.
'If Folder name in English is
'Public Folders\All Public Folders\Big Store A Calendar or
‘'Public Folders\All Public Folders\Big Store B Calendar
Public Function GetPublicFolder(strFolderPath)
Dim colFolders
Dim objFolder
Dim arrFolders
Dim i
On Error Resume Next
strFolderPath = Replace(strFolderPath, "/", "\")
arrFolders = Split(strFolderPath, "\")
Set objFolder = Application.Session.GetDefaultFolder(18) ‘This is the correct folder # for “All Public Folders”
Set objFolder = objFolder.Folders.Item(arrFolders(0))
If Not objFolder Is Nothing Then
For i = 1 To UBound(arrFolders)
Set colFolders = objFolder.Folders
Set objFolder = Nothing
Set objFolder = colFolders.Item(arrFolders(i))
If objFolder Is Nothing Then
Exit For
End If
Next
End If
Set GetPublicFolder = objFolder
Set colFolders = Nothing
' Set objApp = Nothing
Set objFolder = Nothing
End Function
Application in Set objFolder = Application.Session.GetDefaultFolder(18) is Excel. You want to use Outlook.
Sub DisplyOutlookPublicFolderFromExcel()
Dim olApp As Outlook.Application
Dim olAppItem As Outlook.AppointmentItem
Dim pubCal As Folder
Set olApp = CreateObject("Outlook.Application")
Set pubCal = GetPublicFolder(olApp, "All Public Folders\Big Store A Calendar")
pubCal.Display
Set olAppItem = Nothing
Set olApp = Nothing
Set pubCal= Nothing
End Sub
Public Function GetPublicFolder(objApp, strFolderPath)
Dim colFolders
Dim objFolder
Dim arrFolders
Dim i
On Error Resume Next
strFolderPath = Replace(strFolderPath, "/", "\")
arrFolders = Split(strFolderPath, "\")
Set objFolder = objApp.Session.GetDefaultFolder(18) 'This is the correct folder # for “All Public Folders”
Set objFolder = objFolder.Folders.Item(arrFolders(0))
If Not objFolder Is Nothing Then
For i = 1 To UBound(arrFolders)
Set colFolders = objFolder.Folders
Set objFolder = Nothing
Set objFolder = colFolders.Item(arrFolders(i))
If objFolder Is Nothing Then
Exit For
End If
Next
End If
Set GetPublicFolder = objFolder
Set colFolders = Nothing
Set objApp = Nothing
Set objFolder = Nothing
End Function

Move a specific number of emails from shared Outlook folder

Every few days I manually move a specified number of emails from a shared network mailbox to subfolders of team managers. They want them moved from oldest to newest. Both the managers and the number can change each time.
I wrote a script for moving a small number of emails with a specific subject line in the folder to a subfolder to be worked by a certain group.
I have tried to adapt this to my current task.
Sub Moverdaily()
On Error GoTo errHandler
Dim olApp As Outlook.Application
Dim objNS As Outlook.Namespace
Dim olFolder As Outlook.MAPIFolder
Dim msg As Outlook.MailItem
Dim manager= As Outlook.MAPIFolder
Dim cell,start,finish,rng As Range
Dim countE,countM As Integer
Dim emcount, casecount, movedcount
Set rng = Range(Range("A2"), Range("A2").End(xlDown))
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
Set olFolder = objNS.Folders("Documents").Folders("Inbox")
Set manager = objNS.Folders("Document").Folders("Inbox").Folders("Manager")
Set finish = ThisWorkbook.Sheets("Mover").Range("I11")
Set start = ThisWorkbook.Sheets("Mover").Range("I10")
start.Value = Format(Now, "hh:mm:ss")
Set emcount = Range("I12")
Set casecount = Range("I13")
Set movedcount = Range("I14")
countM = 0
countE = 0
For i = olFolder.Items.count To 1 Step -1
For Each cell In rng
If (cell.Text = (onlyDigits(msg.Subject))) Then
msg.move manager
countM = 1 + countM
cell.Offset(0, 1).Value = "Moved"
End If
Next
countE = 1 + countE
Next
finish.Value = Format(Now, "hh:mm:ss")
emcount.Value = countE
casecount.Value = rng.count
movedcount.Value = countM
errHandler:
MsgBox ("Error " & Err.Number & ": " & Err.Description)
Exit Sub
End Sub
Firstly, do not use "for each" with a collection that you change - MailItem.Mpve removes an itemn from that collection. Use a for i = Items.Count to 1 step -1 instead.
Secondly, do not loop through all item - if you already know the entry ids (rngarry), simply call Namespace.GetItemfromID.

Convert Early Binding VBA to Late Binding VBA : Excel to Outlook Contacts

Each employee gets an updated contact list. I'm creating a macro in Excel that will delete all outlook contacts, then import all the contacts on that sheet into their main outlook contacts. Not all users are on the same outlook version, so I can't use Early Binding methods since the Outlook OBJ Library cannot be referenced between versions.
I managed to get my delete loop into late binding easily, but I'm having trouble getting the import code to work in late binding. Here is the working early binding method I currently have for the import:
Dim olApp As Outlook.Application
Dim olNamespace As Outlook.Namespace
Dim olFolder As Outlook.MAPIFolder
Dim olConItems As Outlook.Items
Dim olItem As Object
'Excel objects.
Dim wbBook As Workbook
Dim wsSheet As Worksheet
'Location in the imported contact list.
Dim lnContactCount As Long
Dim strDummy As String
'Turn off screen updating.
Application.ScreenUpdating = False
'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets(1)
'Format the target worksheet.
With wsSheet
.Range("A1").CurrentRegion.Clear
.Cells(1, 1).Value = "Company / Private Person"
.Cells(1, 2).Value = "Street Address"
.Cells(1, 3).Value = "Postal Code"
.Cells(1, 4).Value = "City"
.Cells(1, 5).Value = "Contact Person"
.Cells(1, 6).Value = "E-mail"
With .Range("A1:F1")
.Font.Bold = True
.Font.ColorIndex = 10
.Font.Size = 11
End With
End With
wsSheet.Activate
'Initalize the Outlook variables with the MAPI namespace and the default Outlook folder of the current user.
Set olApp = New Outlook.Application
Set olNamespace = olApp.GetNamespace("MAPI")
Set olFolder = olNamespace.GetDefaultFolder(10)
Set olConItems = olFolder.Items
'Row number to place the new information on; starts at 2 to avoid overwriting the header
lnContactCount = 2
'For each contact: if it is a business contact, write out the business info in the Excel worksheet;
'otherwise, write out the personal info.
For Each olItem In olConItems
If TypeName(olItem) = "ContactItem" Then
With olItem
If InStr(olItem.CompanyName, strDummy) > 0 Then
Cells(lnContactCount, 1).Value = .CompanyName
Cells(lnContactCount, 2).Value = .BusinessAddressStreet
Cells(lnContactCount, 3).Value = .BusinessAddressPostalCode
Cells(lnContactCount, 4).Value = .BusinessAddressCity
Cells(lnContactCount, 5).Value = .FullName
Cells(lnContactCount, 6).Value = .Email1Address
Else
Cells(lnContactCount, 1) = .FullName
Cells(lnContactCount, 2) = .HomeAddressStreet
Cells(lnContactCount, 3) = .HomeAddressPostalCode
Cells(lnContactCount, 4) = .HomeAddressCity
Cells(lnContactCount, 5) = .FullName
Cells(lnContactCount, 6) = .Email1Address
End If
wsSheet.Hyperlinks.Add Anchor:=Cells(lnContactCount, 6), _
Address:="mailto:" & Cells(lnContactCount, 6).Value, _
TextToDisplay:=Cells(lnContactCount, 6).Value
End With
lnContactCount = lnContactCount + 1
End If
Next olItem
'Null out the variables.
Set olItem = Nothing
Set olConItems = Nothing
Set olFolder = Nothing
Set olNamespace = Nothing
Set olApp = Nothing
'Sort the rows alphabetically using the CompanyName or FullName as appropriate, and then autofit.
With wsSheet
.Range("A2", Cells(2, 6).End(xlDown)).Sort key1:=Range("A2"), order1:=xlAscending
.Range("A:F").EntireColumn.AutoFit
End With
'Turn screen updating back on.
Application.ScreenUpdating = True
MsgBox "The list has successfully been created!", vbInformation
End Sub
To use Late binding, you should declare all your Outlook-specific objects as Object:
Dim olApp As Object, olNamespace As Object, olFolder As Object, olConItems As Object
Then:
Set olApp = CreateObject("Outlook.Application")
This will make each computer create the olApp object from the Outlook library that is installed on it. It avoids you to set an explicit reference to Outlook14 in the workbook that you will distribute (remove that reference from the project before distributing the Excel file).
Hope this helps :)
All of your Outlook object declarations would first have to become non-Oulook related object declarations.
Dim olApp As Object
Dim olNamespace As Object
Dim olFolder As Object
Dim olConItems As Object
Dim olItem As Object
You will need a CreateObject function on the Outlook.Application object.
Set olApp = CreateObject("Outlook.Application")
Everything else should fall into place.

Resources