A1VBCode Forums

Object variable or With block variable not set


http://www.a1vbcode.com/vbforums/Topic31554.aspx

By joeltang - 7/30/2012

This is a script for Outlook and it works until I add the objMail.Send command then I get the "Object variable or With block variable not set" error.

Anyone know why?



code: http://pastebin.com/9Y01zVZ6



or here:



Sub Forward1()

Dim objMail As Outlook.MailItem

Set objItem = GetCurrentItem()

Set objMail = objItem.Forward

objMail.To = "yourtoodledoemail@toodledo.com"

objMail.Subject = objMail.Subject & "! @context $Status +Goals *Project"

objMail.Display

Set objItem = Nothing

Set objMail = Nothing

objMail.Send

Call MoveToProjectFolder

End Sub



Function GetCurrentItem() As Object

Dim objApp As Outlook.Application

Set objApp = Application

On Error Resume Next

Select Case TypeName(objApp.ActiveWindow)

Case "Explorer"

Set GetCurrentItem = _

objApp.ActiveExplorer.Selection.Item(1)

Case "Inspector"

Set GetCurrentItem = _

objApp.ActiveInspector.CurrentItem

Case Else

End Select

End Function





'Outlook VB Macro to move selected mail item(s) to a target folder

Sub MoveToProjectFolder()

On Error Resume Next



Dim ns As Outlook.NameSpace

Dim moveToFolder As Outlook.MAPIFolder

Dim objItem As Outlook.MailItem



Set ns = Application.GetNamespace("MAPI")



'Define path to the target folder

Set moveToFolder = ns.Folders("Your inbox").Folders("FolderName").Folders("SubfolderName")



If Application.ActiveExplorer.Selection.Count = 0 Then

MsgBox ("No item selected")

Exit Sub

End If



If moveToFolder Is Nothing Then

MsgBox "Target folder not found!", vbOKOnly + vbExclamation, "Move Macro Error"

End If



For Each objItem In Application.ActiveExplorer.Selection

If moveToFolder.DefaultItemType = olMailItem Then

If objItem.Class = olMail Then

objItem.Move moveToFolder

End If

End If

Next



Set objItem = Nothing

Set moveToFolder = Nothing

Set ns = Nothing



End Sub
By joeltang - 7/31/2012

I found my error. I think I was clearing objMail before trying to use it.

I don't code often. Tongue



I went from this:

Set objItem = Nothing

Set objMail = Nothing

objMail.Send



to this:

objMail.Send

Set objItem = Nothing

Set objMail = Nothing