Excel to create task in Outlook - vba

I am relatively new to VBA and so I'm sure this is a basic mistake that I am making!
A1 contains valid date, A2 contains task information, A3 contains number of days before A1 date to trigger task reminder.
The problem is when I put =addtotasks(A1,A2,A3)
It just comes up with #NAME?
I have enabled the Microsoft Outlook 14.0 Object Library in the references.
I am based in the UK telling you for dates purposes.
This is the following code. I have included some extra code for setting a remainder only on a business day.
'Function NextBusinessDay(dateFrom As Date, _
Optional daysAhead As Long = 1) As Date
Dim currentDate As Date
Dim nextDate As Date
' convert neg to pos
If daysAhead < 0 Then
daysAhead = Abs(daysAhead)
End If
' determine next date
currentDate = dateFrom
nextDate = DateAdd("d", daysAhead, currentDate)
' is next date a weekend day?
Select Case Weekday(nextDate, vbUseSystemDayOfWeek)
Case vbSunday
nextDate = DateAdd("d", 1, nextDate)
Case vbSaturday
nextDate = DateAdd("d", 2, nextDate)
End Select
NextBusinessDay = CDate(Int(nextDate))
End Function
Dim bWeStartedOutlook As Boolean
Function AddToTasks(strDate As String, strText As String, DaysOut As Integer) As Boolean
' Adds a task reminder to Outlook Tasks a specific number of days before the date specified
' Returns TRUE if successful ' Will not trigger OMG because no protected properties are accessed
'
' Usage:
' =AddToTasks("12/31/2008", "Something to remember", 30)
' or:
' =AddToTasks(A1, A2, A3)
' where A1 contains valid date, A2 contains task information, A3 contains number of days before A1 date to trigger task reminder '
' can also be used in VBA :
'If AddToTasks("12/31/2008", "Christmas shopping", 30) Then
' MsgBox "ok!"
'End If
Dim intDaysBack As Integer
Dim dteDate As Date
Dim olApp As Object 'Outlook.Application
Dim objTask As Object ' Outlook.TaskItem
' make sure all fields were filled in
If (Not IsDate(strDate)) Or (strText = "") Or (DaysOut <= 0) Then
AddToTasks = False
GoTo ExitProc
End If
' We want the task reminder a certain number of days BEFORE the due date
' ex: if DaysOut = 120, then we want the due date to be -120 before the date specified
' we need to pass -120 to the NextBusinessDay function, so to go from 120 to -120,
' we subtract double the number (240) from the number provided (120).
' 120 - (120 * 2); 120 - 240 = -120
intDaysBack = DaysOut - (DaysOut * 2)
dteDate = NextBusinessDay(CDate(strDate), intDaysBack)
On Error Resume Next
Set olApp = GetOutlookApp
On Error GoTo 0
If Not olApp Is Nothing Then
Set objTask = olApp.CreateItem(3) ' task item
With objTask
.StartDate = dteDate
.Subject = strText & ", due on: " & strDate
.ReminderSet = True
.Save
End With
Else
AddToTasks = False
GoTo ExitProc
End If
' if we got this far, it must have worked
AddToTasks = True
ExitProc:
If bWeStartedOutlook Then
olApp.Quit
End If
Set olApp = Nothing
Set objTask = Nothing
End Function
Function GetOutlookApp() As Object
On Error Resume Next
Set GetOutlookApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
Set GetOutlookApp = CreateObject("Outlook.Application")
bWeStartedOutlook = True
End If
On Error GoTo 0
End Function
I have taken this code from this website, by the way:
http://www.jpsoftwaretech.com/get-previous-business-day-in-vba/

The #Name? error happens when you reference a function or variable unknown to the program. It's not sure where this function resides. Try using the "fx" button next to the formula bar and selecting user defined functions, it should be listed there.
My guess is you created this function in a different work book probably the personal.xlsb.
In order to use user defined functions you have to reference the full path to them. Try reading the last paragraph here:
http://office.microsoft.com/en-us/excel-help/creating-custom-functions-HA001111701.aspx

Related

Property of an object, expected be a mailitem, generates '438' Run-time error: "Object doesn't support this property or method"

I'm trying to choose a folder then show a MsgBox with the number of emails sent during a set timeframe in that folder and all it's subfolders.
I can select a folder but I get
'438' Run-time error: "Object doesn't support this property or method"
on the line after the "for" loop.
receive_datetime = objCurrentFolder.Items(i).SentOn
This is the whole macro:
Sub CountItems()
Dim lItemsCount As Long
StartDate = DateSerial(2018, 1, 1)
EndDate = DateSerial(2020, 1, 1)
'Select a folder
Set objMainFolder = Outlook.Application.Session.PickFolder
If objMainFolder Is Nothing Then
MsgBox "You choose select a valid folder!", _
vbExclamation + vbOKOnly, "Warning for Pick Folder"
Else
'Initialize the total count
lItemsCount = 0
Call LoopFolders(objMainFolder, lItemsCount)
End If
'Display a message for the total count
MsgBox "There are " & lItemsCount & " items in the " & _
objMainFolder.Name & " folder Including its subfolders.", _
vbInformation, "Count Items"
End Sub
Sub LoopFolders(ByVal objCurrentFolder As Outlook.Folder, lCurrentItemsCount As Long)
Dim objSubfolder As Outlook.Folder
Set receiveditems = objCurrentFolder.Items
For i = receiveditems.Count To 1 Step -1
' the last item in the collection is your most recent email.
' This can be handy to know if your inbox is massive and
' you want to include a Exit For at some point,
' e.g. when you run into a date < StartDate
receive_datetime = objCurrentFolder.Items(i).SentOn
If receive_datetime >= StartDate And receive_datetime <= EndDate Then
lCurrentItemsCount = lCurrentItemsCount + 1
End If
Next i
'Process all folders and subfolders recursively
If objCurrentFolder.Folders.Count Then
For Each objSubfolder In objCurrentFolder.Folders
Call LoopFolders(objSubfolder, lCurrentItemsCount)
Next
End If
End Sub
Thanks to Tim Williams helping me out. I think I got it to work by checking if it's a MailItem or not.
Select Case True
Case TypeOf objCurrentFolder.Items(i) Is Outlook.MailItem
receive_datetime = objCurrentFolder.Items(i).SentOn
If receive_datetime >= StartDate And receive_datetime <= EndDate Then
lCurrentItemsCount = lCurrentItemsCount + 1
End If
Case Else
lCurrentItemsCount = lCurrentItemsCount + 0
End Select

Excel VBA code only works in debug mode

I've already searched in a bunch of topics and no solution seemed to work for me.
I've an Excel macro file that sometimes works fine, but sometimes only works in stepping mode.
This is a sub inside a main sub that passes a value (message) to a spreadsheet from an Outlook Calendar by category (key). (for this code I adapted from Script to total hours by calendar category in Outlook) .The value goes into the row with the same name as the category and the week value in the column. I've tried the DoEvents and I thought it had worked, but when I tried to run it in a different computer it failed again.
Any ideas?
Option Explicit
Public keyArray
Sub totalCategories()
Dim app As New Outlook.Application
Dim namespace As Outlook.namespace
Dim calendar As Outlook.Folder
Dim appt As Outlook.AppointmentItem
Dim apptList As Outlook.Items
Dim apptListFiltered As Outlook.Items
Dim startDate As String
Dim endDate As String
Dim category As String
Dim duration As Integer
Dim outMsg As String
Dim firstDayOfTheYear As Date
'Going to be used to get start and end date
firstDayOfTheYear = Date
firstDayOfTheYear = "01/01/" & Right(firstDayOfTheYear, 4)
' Access appointment list
Set namespace = app.GetNamespace("MAPI")
Set calendar = namespace.GetDefaultFolder(olFolderCalendar)
Set apptList = calendar.Items
' Include recurring appointments and sort the list
apptList.IncludeRecurrences = True
apptList.Sort "[Start]"
' Get selected date
startDate = firstDayOfTheYear + 7 * (CInt(SelectWeek.week) - 1)
endDate = firstDayOfTheYear + 7 * (CInt(SelectWeek.week) - 1) + 6
startDate = Format(startDate, "dd/MM/yyyy") & " 00:01"
endDate = Format(endDate, "dd/MM/yyyy") & " 11:59 PM"
' Filter the appointment list
Dim strFilter As String
strFilter = "[Start] >= '" & startDate & "'" & " AND [End] <= '" & endDate & "'"
Set apptListFiltered = apptList.Restrict(strFilter)
' Loop through the appointments and total for each category
Dim catHours
Set catHours = CreateObject("Scripting.Dictionary")
For Each appt In apptListFiltered
category = appt.Categories
duration = appt.duration
If catHours.Exists(category) Then
catHours(category) = catHours(category) + duration
Else
catHours.Add category, duration
End If
Next
' Loop through the categories
Dim key
keyArray = catHours.Keys
DoEvents 'prevents a bug from happening --> in some cases the total hours weren't divided by categories
For Each key In keyArray
outMsg = catHours(key) / 60
'Print in Realizado sheet --> activities must be in range (name manager) as "atividades"
writeReport SelectWeek.week, outMsg, key
Next
' Clean up objects
Set app = Nothing
Set namespace = Nothing
Set calendar = Nothing
Set appt = Nothing
Set apptList = Nothing
Set apptListFiltered = Nothing
End Sub
Sub writeReport(week, message As String, key)
Dim ws As Worksheet
Dim i As Integer
Dim Activities, nActivities As Integer
Set ws = Sheets("5")
Activities = Range("activities")
nActivities = UBound(Activities)
DoEvents
For i = 1 To nActivities
DoEvents
If key = Cells(i + 8, 2).Value Then
ws.Cells(i + 8, week + 3).Value = CDbl(message)
Exit For
End If
Next i
End Sub
You need to handle errors explicitly so you know exactly what is going on. Trust me that this will save you HEAPS of time troubleshooting your own code, especially in VBA.
Common practice is something like "try, catch, finally".
Dim position as string
Sub foo()
position = "sub function short description"
On Error GoTo catch
Err.Clear
'do stuff
finally:
On Error Resume Next
'do cleanup stuff
Exit Sub
catch:
Debug.Print Right(ThisWorkbook.FullName, Len(ThisWorkbook.FullName) - 3) & ", _
Position: " & errorPosition & " , Error Code: [ " & Hex(Err.number) & "], _
Description: " & Err.Description & ""
Resume finally
End Sub
Problem solved!
From this:
If key = Cells(i + 8, 2).Value Then
ws.Cells(i + 8, week + 3).Value = CDbl(message)
Exit For
End If
To this:
If key = Activities(i, 1) Then
ws.Cells(i + 8, week + 3).Value = CDbl(message)
Exit For
End If

Timeline Slicer Excel 2013 VBA

hoping someone can help
I'm trying to call a timeline slicer value in vba so I can control other slicers. I have managed it from cells but I was wondering if it can be controlled by my master slicer
Sub Slicer_Time_Change()
Dim startDate As Date, endDate As Date
startDate = Range("A1") 'Set slicer 1 start date as slicer selection instead
endDate = Range("B1") 'Set slicer 1 End date as slicer selection instead
ActiveWorkbook.SlicerCaches("NativeTimeline_Date1").TimelineState. _
SetFilterDateRange startDate, endDate
ActiveWorkbook.SlicerCaches )("NativeTimeline_Date2").TimelineState. _
SetFilterDateRange startDate, endDate
End Sub
Many thanks in advance!
Going to answer this one myself!
Sub Slicer_Time_Change()
'Gets data from master slicer selection
Set cache = ActiveWorkbook.SlicerCaches("NativeTimeline_Date1")
'Puts into cell
Cells(1, 1) = cache.TimelineState.startDate
Cells(1, 2) = cache.TimelineState.endDate
Dim startDate As Date, endDate As Date
startDate = Range("A1")
endDate = Range("B1")
'Takes data from cell and controls other slicers with date range
ActiveWorkbook.SlicerCaches("NativeTimeline_Date2").TimelineState. _
SetFilterDateRange startDate, endDate
End Sub
I had the same problem. Your answer helped but I needed this triggered when the master slicer changed. Unfortunately slicers have no events, but the PivotTables they impact do. The code below will update all other timeline slicers when the master slicer changes which, in turn, changes its PivotTable, which can then be used to trigger changes to all other slicers.
Private Sub Workbook_SheetPivotTableUpdate(ByVal Sh As Object, ByVal Target As PivotTable)
' Description:Update Timeline Slicers from Master Slicer
' Inputs: Sh PivotTable's worksheet
' Target PivotTable being changed/updated
' Outputs: *None
' Requisites: *None
' Example: *None - This is an event handler found in ThisWorkbook module
' Date Ini Modification
' 10/19/16 CWH Initial Development
' Declarations
Const cRoutine As String = "Workbook_SheetPivotTableUpdate"
Dim oSlicer As SlicerCache 'Current Slicer
Const cSlicer As Long = 1 'Master Slicer
Dim dStartDate As Date 'Start Date
Dim dEndDate As Date 'End Date
Dim bCleared As Boolean 'Filter Cleared Flag
Dim bEvents As Boolean 'Events Enabled Flag
' Error Handling Initialization
On Error GoTo ErrHandler
' Prevent cascading events
bEvents = Application.EnableEvents
Application.EnableEvents = False
' Get Master Slicer's dates
Set oSlicer = ThisWorkbook.SlicerCaches(cSlicer)
bCleared = oSlicer.FilterCleared
If Not bCleared Then
With oSlicer.TimelineState
dStartDate = .FilterValue1
dEndDate = .FilterValue2
End With
End If
' Set All other Timeline Slicer Dates
For Each oSlicer In ThisWorkbook.SlicerCaches
If oSlicer.SlicerCacheType = xlTimeline And _
oSlicer.Index <> cSlicer Then
If bCleared Then _
oSlicer.ClearAllFilters Else _
oSlicer.TimelineState.SetFilterDateRange _
StartDate:=dStartDate, EndDate:=dEndDate
End If
Next
ErrHandler:
Select Case Err.Number
Case Is = 0: 'Do nothing
Case Is = 9: 'Do Nothing Master Slicer Missing
Case Else:
Select Case MsgBox(Prompt:=Err.Description, _
Buttons:=vbAbortRetryIgnore, _
Title:=cRoutine, _
HelpFile:=Err.HelpFile, _
Context:=Err.HelpContext)
Case Is = vbAbort: Stop: Resume 'Debug mode - Trace
Case Is = vbRetry: Resume 'Try again
Case Is = vbIgnore: 'End routine
End Select
End Select
' Clean up: Resume responding to events
Application.EnableEvents = bEvents
End Sub
Option Explicit
Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
If Target = "TopElementOfSum" Then
ActiveWorkbook.SlicerCaches("NativeTimeline_Date1").TimelineState.SetFilterDateRange ActiveWorkbook.SlicerCaches("NativeTimeline_Date").TimelineState.StartDate, ActiveWorkbook.SlicerCaches("NativeTimeline_Date").TimelineState.EndDate
'NativeTimeline_Date1 to numer slidera w systemie nie jego nazwa, kiedys dlugo sie z tym jebalem bo nie wiedzialem co jest 5
End If
End Sub
Works for me, just SlicerCaches("NativeTimeline_Date") refers to internal numbering of Time Lines, no names of them.

Does my parameter value store its value i.e. memory - if button clicked divert macro to second macro

Here is my code of two sub procedures, one function, two other sub procedures for macro protection (irrelevant). The last sub procedure, sub manual_date() is the center of my inquiry. How could I divert the macro code if the user of this macro choose to manually input their own date. The main code is highlighted as the center code screen. I know I could very easily copy and paste as a solution. I am interested in an advanced coding strategy.
Option Explicit
Sub Client_Dirty_Recon()
Dim Date_minus_one As Date ' Date & weekend logic
Dim answer As Long ' Date & weekend logic
Dim brow As Long ' Last filled cell in column
Dim yrow As Long ' Last filled cell in column
Dim nRow As Long ' Last filled cell in column
Dim c As Range ' rngWatch.Cells(i, 1).Value
Dim oldStatusBar As Variant ' Save StatusBar status
Dim Client_path As String ' Range("Path")
Dim wb As Workbook ' ThisWorkbook
Dim wbDirty As Workbook ' Workbooks.Open(Client_path)
Dim rngReconcile As Range ' wb.Sheets(1).Range("K:K")
Dim rngWatch As Range ' wbDirty.Sheets(1).Range("A:A")
Dim rngNew As Range ' wbNew.Sheets(1).Range("A:A")
Dim failed_count As Long
Dim FS
oldStatusBar = Application.DisplayStatusBar 'optional - save StatusBar
Application.DisplayStatusBar = True 'optional - turn on StatusBar
Application.ScreenUpdating = False 'optional - screen won't flash
Application.StatusBar = "Opening workbooks..." 'optional - Update user
Call Unprot
Date_minus_one = Date
answer = IsMonday(Date_minus_one)
If answer = True Then
Date_minus_one = Date - 3
Else
Date_minus_one = Date - 1
End If
Set FS = CreateObject("Scripting.FileSystemObject")
Set wb = ThisWorkbook
' Client_path = wb.Names("Path").RefersToRange.Value ' use path as defined name on sheet
Client_path = "XXXXXXX " & Format(Date_minus_one, "mmddyyyy") & ".xls"
If FS.fileexists(Client_path) Then
' Get only used part of column
Set rngReconcile = wb.Sheets(1).Range("K:K")
nRow = rngReconcile(rngReconcile.Cells.Count).End(xlUp).Row ' Get last filled cell
Set rngReconcile = Range(rngReconcile(1), rngReconcile(nRow)) ' Reduce rng size
Set wbDirty = Workbooks.Open(Client_path) ' Assumes it exists and is not open
' Get only used part of column
Set rngWatch = wbDirty.Sheets(1).Range("A:A")
nRow = rngWatch(rngWatch.Cells.Count).End(xlUp).Row ' Get last filled cell
Set rngWatch = Range(rngWatch(3), rngWatch(nRow)) ' Reduce range size
Set rngNew = wb.Sheets("Client Watchlist").Range("K:K")
brow = rngNew(rngNew.Cells.Count).End(xlUp).Row
Set rngNew = Range(rngNew(2), rngNew(brow))
rngNew.ClearContents
Set rngNew = wb.Sheets(1).Range("K:K")(rngNew.Cells.Count).End(xlUp)(2)
For Each c In rngWatch ' Each value in rngWatch
On Error Resume Next ' Interrupt Error checking
If IsError(WorksheetFunction.Match( _
c.Value, rngReconcile, 0)) Then ' If not in rngReconcile
rngNew.FormulaR1C1 = c.Value ' Copy to rngNew
Set rngNew = rngNew(2) ' Moves range down =Offset(rngNew,1,0)
End If
On Error GoTo 0 ' Reset Error checking
If (c.Row + 1) Mod 100 = 0 Then ' Optional - Update user
Application.StatusBar = "Evaluating cell " & c(2).Address & "..."
End If
Next c
Application.StatusBar = False
Application.DisplayStatusBar = oldStatusBar ' Reset Status Bar
ActiveWindow.Close Savechanges:=False ' Closes client email
MsgBox ("Reconcilied to ") & Client_path & " on " & Now
Else
MsgBox ("Please save down ") & Client_path, vbCritical
End If
Call Prot
Application.ScreenUpdating = True ' Turn back on
End Sub
Public Function IsMonday(inputdate As Date) As Boolean
Select Case Weekday(inputdate)
Case vbMonday
IsMonday = True
Case Else
IsMonday = False
End Select
End Function
Sub manual_date()
manual_date_input = InputBox("Enter Date (MMDDYYYY")
End Sub
Update
I added the following two sub procedures which shall pass the dt parameter as instructed below. I feel as if this variable dt as date is storing a value? I am able to run the sub procedure Sub RunWithUserDate() but the Sub RunWithDefault() procedure does not run smoothly. I have inserted several message boxes to view the value of dt. Should I be resetting the value of this date variable? If so, how could I? (Please note, I have cleaned up the code within the main sub procedure Sub Client_Dirty_Recon() and I have properly assigned the dt variable within the client_path variable.
Sub test2()
MsgBox Date
MsgBox dt
MsgBox IsMonday(dt)
IsMonday (dt)
MsgBox (dt)
End Sub
Public Function IsMonday(inputdate As Date) As Boolean
Select Case Weekday(inputdate)
Case vbMonday
dt = Date - 3 ' IsMonday = True
'dt = Format(dt, "mmddyyyy")
Case Else
dt = Date - 1
'dt = Format(Date - 1, "mmddyyyy") ' IsMonday = False
'dt = Format(dt, "mmddyyyy")
End Select
End Function
Sub RunWithDefault() ' Button 1: use current date
'CHECK THIS AGAIN ***ALSO ADD PERMISSIONS IF NECESSARY
MsgBox IsMonday(dt)
MsgBox dt
Client_Dirty_Recon IsMonday(dt)
End Sub
' Button 2: get date from user
Sub RunWithUserDate() ' Get dt value from user
'PROMPT USER FOR PASSWORD
dt = Application.InputBox("Enter Date (MM/DD/YYYY)", "Manual Override")
'du = Format(du, "mmddyyyy")
'du = Format(Application.InputBox("Enter Date (MM/DD/YYYY)"), "mmddyyyy")
'dt = Format(dt, "mmddyyyy")
'MsgBox dt
Client_Dirty_Recon dt
'dt = Date
End Sub
Add a Date parameter to your main sub, and have (e.g.) two separate buttons, each linked to smaller "stubs" which in turn will call the main code. First one would pass the current date; second one would pass a date sourced from the user somehow.
'button 1: use current date
Sub RunWithDefault()
Client_Dirty_Recon Date
End Sub
'button 2: get date from user
Sub RunWithUserDate()
Dim dt As Date
'get dt value from user
Client_Dirty_Recon dt
End Sub
'main code
Sub Client_Dirty_Recon(dt as Date)
'run main processing
End Sub

VBA - Compile Error, Expected: line number or label or statement or end of statement

I want to use Excel VBA to set up Task Reminders in Outlook, so I found this code from here:
http://www.jpsoftwaretech.com/using-excel-vba-to-set-up-task-reminders-in-outlook/
Dim bWeStartedOutlook As Boolean
Function AddToTasks(strDate As String, strText As String, DaysOut As Integer) As Boolean
=AddToTasks(B2, M2 Time, 120)
' Adds a task reminder to Outlook Tasks a specific number of days before the date specified
' Returns TRUE if successful
' Will not trigger OMG because no protected properties are accessed
' by Jimmy Pena, http://www.jpsoftwaretech.com, 10/30/2008
'
' Usage:
' =AddToTasks("12/31/2008", "Something to remember", 30)
' or:
' =AddToTasks(A1, A2, A3)
' where A1 contains valid date, A2 contains task information, A3 contains number of days before A1 date to trigger task reminder
'
' can also be used in VBA :
'If AddToTasks("12/31/2008", "Christmas shopping", 30) Then
'  MsgBox "ok!"
'End If
 
Dim intDaysBack As Integer
Dim dteDate As Date
Dim olApp As Object ' Outlook.Application
Dim objTask As Object ' Outlook.TaskItem
 
' make sure all fields were filled in
If (Not IsDate(strDate)) Or (strText = "") Or (DaysOut <= 0) Then
  AddToTasks = False
  GoTo ExitProc
End If
 
' We want the task reminder a certain number of days BEFORE the due date
' ex: if DaysOut = 120, then we want the due date to be -120 before the date specified
' we need to pass -120 to the NextBusinessDay function, so to go from 120 to -120,
' we subtract double the number (240) from the number provided (120).
' 120 - (120 * 2); 120 - 240 = -120
 
intDaysBack = DaysOut - (DaysOut * 2)
 
dteDate = NextBusinessDay(CDate(strDate), intDaysBack)
 
On Error Resume Next
  Set olApp = GetOutlookApp
On Error GoTo 0
 
If Not olApp Is Nothing Then
  Set objTask = olApp.CreateItem(3)  ' task item
 
  With objTask
    .StartDate = dteDate
    .Subject = strText & ", due on: " & strDate
    .ReminderSet = True
    .Save
  End With
 
Else
  AddToTasks = False
  GoTo ExitProc
End If
 
' if we got this far, it must have worked
AddToTasks = True
 
ExitProc:
If bWeStartedOutlook Then
  olApp.Quit
End If
Set olApp = Nothing
Set objTask = Nothing
End Function
 
Function GetOutlookApp() As Object
 
On Error Resume Next
  Set GetOutlookApp = GetObject(, "Outlook.Application")
  If Err.Number <> 0 Then
    Set GetOutlookApp = CreateObject("Outlook.Application")
    bWeStartedOutlook = True
  End If
On Error GoTo 0
 
End Function
Sub Test()
My question is, if I have all the data in the spreadsheet, and I initiallize AddToTasks like so:
=AddToTasks(A1, A2, 120)
Why does it come up with that error?
You need to call AddToTasks from a separate Subroutine. (Right now you are trying to call it from inside itself.) So, create a separate Subroutine something like this:
Sub CallAddToTasksFunction
If AddToTasks("12/31/2008", "Something to remember", 30) = True Then
Debug.Print "Task Added"
Else
Debug.Print "Failed"
End If
End Sub
AddToTasks returns True or False depending on if it succeeded. You can see where that happens in a couple of spots in the function where the code is like:
AddToTasks = False (or True)
and you can see that things like dates that aren't really dates will cause it to fail.