I need help resolving an issue with my code for adding Outlook Tasks. It is functioning correctly on some systems, but not on a machine with Office 365 installed. Specifically, when Outlook is already open on this machine, my code produces an error. However, when Outlook is closed, the code works correctly. What steps can I take to resolve this issue?
procedure CreateOutlookReminder(const Subject, Body, Location: string;
const Start, Duration: TDateTime;
const ReminderMinutesBeforeStart: Integer);
var
Outlook, Calendar, AppointmentItem: OleVariant;
begin
// Connect to Outlook
try
try
Outlook := GetActiveOleObject('Outlook.Application');
except
Outlook := CreateOleObject('Outlook.Application');
end
Except
on E: Exception do
begin
MessageDlg('Unable to add reminder.' + #13#10 +
'The version of outlook on your machine is either unsupported or it does not exist.'
+ E.Message, mtError, [mbOK], 0);
Exit
end;
end;
Calendar := Outlook.GetNamespace('MAPI').GetDefaultFolder(13);
// olFolderCalendar
// Create the Task
AppointmentItem := Calendar.Items.Add; // Task
AppointmentItem.Subject := Subject;
AppointmentItem.Body := Body;
AppointmentItem.remindertime := formatdatetime('mm/dd/yy h:nn:ss ampm',
Duration);
AppointmentItem.duedate := Duration;
// Set the reminder
AppointmentItem.ReminderSet := True;
// Save and display the appointment
AppointmentItem.Save;
Outlook := unAssigned;
end;
Make sure your code is not running with elevated privileges - Outlook is a singleton, so when you call CreateOleObject
(there is no reason to ever call GetActiveOleObject
for Outlook), it returns a pointer to the already running instance. If Outlook and your code are running in different security contexts (e.g., one is running as "Run As Administrator"), the COM system will refuse to marshal the calls.