How to check if sheets exists in this code [duplicate] - excel

This question already has answers here:
Test or check if sheet exists
(23 answers)
Closed 3 years ago.
I have set macro for test mails & move them. But if i get an another excel file, where are another sheet names then I get VBA error: subscript out of range.
The error is in this line: Set xlSheet = xlWB.sheets("MySheet1")
Option Explicit
Sub CheckAttachments(olItem As MailItem)
Const strPath As String = "C:\Users\PC2\Documents\Temp_attachs\"
Const strFindText As String = "Completed"
Dim strFilename As String
Dim olAttach As Attachment
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim bXStarted As Boolean
Dim bFound As Boolean
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myDestFolder = myInbox.Folders("MyFolder1")
If olItem.Attachments.Count > 0 Then
For Each olAttach In olItem.Attachments
If Right(LCase(olAttach.FileName), 4) = "xlsx" Then
strFilename = strPath & Format(olItem.ReceivedTime, "yyyymmdd-HHMMSS") & _
Chr(32) & olAttach.FileName
olAttach.SaveAsFile strFilename
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to read the data
Set xlWB = xlApp.workbooks.Open(strFilename)
Set xlSheet = xlWB.sheets("MySheet1")
If FindValue(strFindText, xlSheet) Then
olItem.Move myDestFolder
'MsgBox "Value found in " & strFilename
bFound = True
End If
xlWB.Close 0
If bXStarted Then xlApp.Quit
If Not bFound Then Kill strFilename
'Exit For
End If
Next olAttach
End If
End Sub
How can i test the sheet and if it's not exists then exit sub (errorhandling: exit sub) ?

To check if the Sheet exists, you can use a code like this:
On Error Resume Next
Set xlSheet = xlWB.Sheets("MySheet1")
If xlSheet Is Nothing Then
MsgBox "Sheet not found!", vbCritical
Exit Sub
End If
On Error GoTo 0
Hope this helps.

You can adjust your code as follows:
Sub foo()
Dim xlSheet As Object
Dim xlWB As Object
On Error Resume Next
Set xlWB = ThisWorkbook
Set xlSheet = xlWB.Sheets("MySheet2")
On Error GoTo 0
If xlSheet Is Nothing Then
Debug.Print "sheet is missing"
Else
Debug.Print "sheet is not missing"
End If
End Sub
Simply shift your "On Error GoTo 0" statement after you set your xlSheet value, and then add another "If" statement to check if you should continue with the rest of your code.

This should Work for you:
Sub CheckAttachments(olItem As MailItem)
Const strPath As String = "C:\Users\PC2\Documents\Temp_attachs\"
Const strFindText As String = "Completed"
Dim strFilename As String
Dim olAttach As Attachment
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim bXStarted As Boolean
Dim bFound As Boolean
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myDestFolder = myInbox.Folders("MyFolder1")
If olItem.Attachments.Count > 0 Then
For Each olAttach In olItem.Attachments
If Right(LCase(olAttach.FileName), 4) = "xlsx" Then
strFilename = strPath & Format(olItem.ReceivedTime, "yyyymmdd-HHMMSS") & _
Chr(32) & olAttach.FileName
olAttach.SaveAsFile strFilename
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to read the data
Set xlWB = xlApp.Workbooks.Open(strFilename)
For Each xlSheet In xlWB.Worksheets
If xlSheet.Name = "MySheet1" Then
Set xlSheet = xlWB.sheets("MySheet1")
Exit For
End If
Next
If xlSheet Is Nothing Then
Exit Sub
End If
If FindValue(strFindText, xlSheet) Then
olItem.Move myDestFolder
'MsgBox "Value found in " & strFilename
bFound = True
End If
xlWB.Close 0
If bXStarted Then xlApp.Quit
If Not bFound Then Kill strFilename
'Exit For
End If
Next olAttach
End If
End Sub

You could use a simple function to check if a sheet name exits:
Function CheckIfSheetExists(Sheetname As String, wb As Workbook) As Boolean
On Error Resume Next
Debug.Print wb.Sheets(Sheetname)
If err.Number <> 0 Then CheckIfSheetExists = False Else CheckIfSheetExists = True
err.clear
End Function
You can call it like so
Sub test()
Dim wbook As Workbook
Dim result As Boolean
Set wbook = Workbooks("Book1")
result = CheckIfSheetExists("Sheet4", wbook)
If result = True Then Msgbox "Sheet exists!"
End Sub
The function will try to print out the name of the specified worksheet within the specified workbook. If this fails, it could not find the worksheet so the function will return False, otherwise it will return True.

Related

Finding last row throws an object required error

What I am trying to do.
I highlight some text in an email then run my macro.
It 'copies' the highlighted text and stores it in variable strText.
Then it creates a file called Artwork List.xlsx if it does not exist and if it exists it opens it.
After that it copies the text into the file in column A row 1 if the lastrow is 1, and if not, it appends to lastrow + 1
My code throws
'Run-time error 424, Object required'
To narrow down, the error should be coming from:
lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
or anything related to this line.
Sub copyArts2File()
MsgBox "ok"
Dim OutApp As Object
Dim OutMail As Object
Dim olInsp As Object
Dim wdDoc As Object
Dim strText As String
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
Dim strTextArr As Variant
On Error Resume Next
'Get Outlook if it's running
Set OutApp = GetObject(, "Outlook.Application")
'Outlook wasn't running, so cancel
If Err <> 0 Then
MsgBox "Outlook is not running so nothing can be selected!"
GoTo lbl_Exit
End If
On Error GoTo 0
Set OutMail = OutApp.ActiveExplorer.Selection.Item(1)
With OutMail
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
strText = wdDoc.Application.Selection.Range.Text
End With
'MsgBox strText
lbl_Exit:
Set OutMail = Nothing
Set OutApp = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
FileName = "Artwork List.xlsx"
fileDoesExist = Dir("C:\Users\quaer\Desktop\DL Arts\" & FileName) > ""
' Check for existing file
If fileDoesExist Then
' Open Excel file
Set xlBook = xlApp.Workbooks.Open("C:\Users\quaer\Desktop\DL Arts\" & FileName)
Set xlSheet = xlBook.Sheets(1)
Else
' Add Excel file
Set xlBook = xlApp.Workbooks.Add
With xlBook
.SaveAs FileName:="C:\Users\quaer\Desktop\DL Arts\" & FileName
End With
Set xlSheet = xlBook.Sheets(1)
End If
' Do stuff with Excel workbook
Dim i As Integer
Dim lastrow As Long
With xlApp
With xlBook
With xlSheet
strTextArr = Split(strText, "Adding file")
lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
MsgBox lastrow
If lastrow = 1 Then
For i = 1 To UBound(strTextArr)
.Range("A" & i).Value = strTextArr(i)
Next i
Else
For i = 1 To UBound(strTextArr)
.Range("A" & (i + lastrow)).Value = strTextArr(i)
Next i
End If
.Close SaveChanges:=True
End With
End With
End With
xlApp.Visible = True
Exit Sub
End Sub
Try replacing this line, lastrow = .Cells(Rows.Count, 1).End(xlUp).Row, with:
lastrow = .Cells(1048576, 1).End(xlUp).Row
or
lastrow = .Cells(Rows.Count +1, 1).End(xlUp).Row
Jeeez this is crazy. I have found the problem finally and got a working code for anyone wanting similar usage. 1st off, I need to add the Microsoft excel add in. So in Outlook VBA, Tools -> references -> check Microsoft Excel 16.0 Object Library. This is to get rid of the 424 object required error, as I was trying to a call a excel built in method I guess. this is the line:
lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
Pls note that I am calling this macro from Outlook.
After this I faced a couple of other issues.
1. errors such as 424 run time, remote server machine does not exist or is not available.
first time running, it throws this error, 2nd time I click, the problem goes away. This is an issue with non specific use of the app, book and worksheet and so leaves VBA to assign on its own. Lesson learnt, be explicit about every thing.
leaves a copy of excel process even after program ends. This can be seen in task manager. This causes issues because then my excel file is linked to this process and not able to open without either read only or notify. Its locked with the process. So I cannot run again next time.
Anyway. Here is the final code. And I have also changed it to .Range instead of .Cells. I believe it does not matter if I used either but the key culprit is : xlSheet.Rows.Count. Instead of just Rows.Count, explicitly use xlSheet.Rows.Count.
Option Explicit
Sub copyArts2File()
MsgBox "ok"
Dim OutApp As Object, OutMail As Object, olInsp As Object, wdDoc As Object
Dim xlApp As Excel.Application, xlBook As Excel.Workbook, xlSheet As Object
Dim strText As String
Dim strTextArr As Variant
Dim fName As String
Dim fileDoesExist As Boolean
Dim i As Integer
Dim lastrow As Long
On Error Resume Next
'Get Outlook if it's running
Set OutApp = GetObject(, "Outlook.Application")
'Outlook wasn't running, so cancel
If Err <> 0 Then
MsgBox "Outlook is not running so nothing can be selected!"
GoTo lbl_Exit
End If
On Error GoTo 0
Set OutMail = OutApp.ActiveExplorer.Selection.Item(1)
With OutMail
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
strText = wdDoc.Application.Selection.Range.Text
End With
'MsgBox strText
'Close out all shit
Set OutMail = Nothing
Set OutApp = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
lbl_Exit:
Set OutMail = Nothing
Set OutApp = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
On Error Resume Next 'Create or use a Excel Application
Set xlApp = GetObject(, "Excel.Application")
If Err.Number > 0 Then Set xlApp = CreateObject("Excel.Application")
On Error GoTo 0
xlApp.Visible = False
xlApp.DisplayAlerts = False
fName = "Artwork List.xlsx"
fileDoesExist = Dir("C:\Users\quaer\Desktop\DL Arts\" & fName) > ""
' Check for existing file
If fileDoesExist Then
' Open Excel file if present
Set xlBook = xlApp.Workbooks.Open("C:\Users\quaer\Desktop\DL Arts\" & fName)
Else
' Add Excel file if not present
Set xlBook = xlApp.Workbooks.Add
xlBook.SaveAs fileName:="C:\Users\quaer\Desktop\DL Arts\" & fName
End If
Set xlSheet = xlBook.Worksheets(1)
' Do stuff with Excel workbook
strTextArr = Split(strText, "Adding file")
lastrow = xlSheet.Range("A" & xlSheet.Rows.Count).End(xlUp).Row
If lastrow = 1 Then
For i = 1 To UBound(strTextArr)
xlSheet.Range("A" & i).Value = strTextArr(i)
Next i
Else
For i = 1 To UBound(strTextArr)
xlSheet.Range("A" & (i + lastrow)).Value = strTextArr(i)
Next i
End If
xlBook.SaveAs fileName:="C:\Users\quaer\Desktop\DL Arts\" & fName, AccessMode:=xlExclusive, ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
xlBook.Close (True)
Set xlBook = Nothing
Set xlSheet = Nothing
xlApp.Visible = True
xlApp.Quit
Set xlApp = Nothing
MsgBox "Done!"
Exit Sub
End Sub
Thanks for the help and suggestions nonetheless.

Export Outlook email data to macro enabled Excel workbook

I have code in Outlook to export data, from emails in a selected folder, to an Excel Workbook.
In that workbook I have VBA code to parse the data (the subject line for now, eventually the body).
When I export from Outlook to a ".xlsx" file everything looks great.
When I export to my ".xlsm" file it adds columns with information that does not align with the correct imported information.
Ex: Column A & B are correct, A is the CreationTime, B is the full SubjectLine
Column C, D, E, etc. will be random parsed bits of subject lines.
Are the macros in the Excel workbook running when the export to Excel is happening?
If so, how can I prevent that?
My Outlook code:
Sub ExportToExcel()
On Error GoTo ErrHandler
Dim appExcel As Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Dim rng As Excel.Range
Dim strSheet As String
Dim strPath As String
Dim intRowCounter As Integer
Dim intColumnCounter As Integer
Dim msg As Outlook.MailItem
Dim nms As Outlook.NameSpace
Dim fld As Outlook.MAPIFolder
Dim itm As Object
'Opens the Workbook and Sheet to paste in
strSheet = "Tester.xlsx"
strPath = "G:\Jason\"
strSheet = strPath & strSheet
Debug.Print strSheet
'Select export folder
Set nms = Application.GetNamespace("MAPI")
Set fld = nms.PickFolder
'Handle potential errors with Select Folder dialog box.
If fld Is Nothing Then
MsgBox "There are no mail messages to export", vbOKOnly, "Error"
Exit Sub
ElseIf fld.DefaultItemType <> olMailItem Then
MsgBox "There are no mail messages to export", vbOKOnly, "Error"
Exit Sub
ElseIf fld.Items.Count = 0 Then
MsgBox "There are no mail messages to export", vbOKOnly, "Error"
Exit Sub
End If
'Open and activate Excel workbook.
Set appExcel = CreateObject("Excel.Application")
appExcel.Workbooks.Open (strSheet)
Set wkb = appExcel.ActiveWorkbook
Set wks = wkb.Sheets(1)
wks.Activate
appExcel.Application.Visible = True
'Copy field items in mail folder.
For Each itm In fld.Items
intColumnCounter = 1
Set msg = itm
intRowCounter = intRowCounter + 1
Set rng = wks.Cells(intRowCounter, intColumnCounter)
rng.Value = msg.CreationTime
intColumnCounter = intColumnCounter + 1
Set rng = wks.Cells(intRowCounter, intColumnCounter)
rng.Value = msg.Subject
Next itm
Set appExcel = Nothing
Set wkb = Nothing
Set wks = Nothing
Set rng = Nothing
Set msg = Nothing
Set nms = Nothing
Set fld = Nothing
Set itm = Nothing
Exit Sub
ErrHandler:
If Err.Number <> 0 Then
MsgBox strSheet & " doesn't exist", vbOKOnly, "Error"
End If
Set appExcel = Nothing
Set wkb = Nothing
Set wks = Nothing
Set rng = Nothing
Set msg = Nothing
Set nms = Nothing
Set fld = Nothing
Set itm = Nothing
End Sub
Parsing code in Excel:
Sub SplitSubjectLine()
Dim text As String
Dim i As Integer
Dim y As Integer
Dim LastRow As Long
Dim name As Variant
ReDim name(3)
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
For y = 1 To LastRow
Cells(y, 2).Select
text = ActiveCell.Value
name = Split(text, ",")
For i = 0 To UBound(name)
Cells(y, i + 2).Value = name(i)
Next i
Next
End Sub
You need to wrap your actions in Excel with :
appExcel.EnableEvents = False (before your actions in Excel) and
appExcel.EnableEvents = True when you are done in Excel
Pseudo code :
''Start of your sub
Set appExcel = CreateObject("Excel.Application")
appExcel.EnableEvents = False
''Your actions in Excel
appExcel.EnableEvents = True
''End of your sub

Scan excel attachment cell(s) for specific text, and forward mail to correct recipient(s)

I am new to using VBA and I adapted code I found online. I am attempting to search an Excel attachment within an e-mail, for specific strings of text in specific cells, and if it finds the correct text, to forward the mail to the correct person.
Sub CheckAttachments(olItem As MailItem)
Const strPath As String = "C:\Users\KoderM16\Desktop"
Const strFindText As String = "Car"
Const strFindText2 As String = "Toy"
Const strFindText3 As String = "Grass"
Dim strFilename As String
Dim olAttach As Attachment
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim bXStarted As Boolean
Dim bFound As Boolean
Dim Inbox As MAPIFolder
Dim MyItems As Items
Dim MyItem As MailItem
Set Inbox = GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Set MyItems = Inbox.Items
Set MyItem = Application.ActiveExplorer.Selection(1)
Set MyItem = MyItem.Forward
If olItem.Attachments.Count > 0 Then
For Each olAttach In olItem.Attachments
If Right(LCase(olAttach.FileName), 3) = "xls" Or Right(LCase(olAttach.FileName), 4) = "xlsx" Then
strFilename = strPath & Format(olItem.ReceivedTime, "yyyymmdd-HHMMSS") & _
Chr(32) & olAttach.FileName
olAttach.SaveAsFile strFilename
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to read the data
Set xlWB = xlApp.Workbooks.Open(strFilename)
Set xlSheet = xlWB.Sheets("Sheet1")
If FindValue(strFindText, xlSheet) Then
MyItem.Recipients.Add "emailaddress1"
MyItem.Send
ElseIf FindValue(strFindText2, xlSheet) Then
MyItem.Recipients.Add "emailaddress2"
MyItem.Send
ElseIf FindValue(strFindText3, xlSheet) Then
MyItem.Recipients.Add "emailaddress3"
MyItem.Send
End If
xlWB.Close 0
If bXStarted Then xlApp.Quit
If Not bFound Then Kill strFilename
Exit For
End If
Next olAttach
End If
End Sub
Function FindValue(FindString As String, iSheet As Object) As Boolean
Dim Rng As Object
If Trim(FindString) <> "" Then
With iSheet.Range("B2")
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=-4163, _
LookAt:=1, _
SearchOrder:=1, _
SearchDirection:=1, _
MatchCase:=False)
If Not Rng Is Nothing Then
FindValue = True
Else
FindValue = False
End If
End With
End If
End Function
Sub Test()
Dim olMsg As MailItem
On Error Resume Next
Set olMsg = ActiveExplorer.Selection.Item(1)
CheckAttachments olMsg
End Sub
The code searches the .xls attachment and if it finds the data in the sheet, it forwards the mail. However, I want to be able to point to multiple individual cells. There might be some unnecessary stuff in the code. I try to point to cell B2 near the bottom of the code but even if it finds the text in A1, it sends the mail.
'Section 1
Sub CheckAttachments(olItem As MailItem)
Const strPath As String = "Enter_Path_Here" 'Define a path for the temp file
Dim strFilename As String
Dim olAttach As Attachment
Dim xlSheet As Object
Dim bXStarted As Boolean
Dim bFound As Boolean
Dim Inbox As MAPIFolder
Dim MyItems As Items
'Section 2
'A new MyItem is required per mutually exclusive recipient as below
Dim MyItem As MailItem
Dim MyItemTwo As MailItem
Dim MyItemThree As MailItem
Dim MyItemFour As MailItem
Dim MyItemFive As MailItem
Dim MyItemSix As MailItem
'Section 3
Set Inbox = GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Set MyItems = Inbox.Items
'Section 4
'A new MyItem is required per mutually exclusive recipient as below
Set MyItem = Application.ActiveExplorer.Selection(1)
Set MyItem = MyItem.Forward
Set MyItemTwo = Application.ActiveExplorer.Selection(1)
Set MyItemTwo = MyItemTwo.Forward
Set MyItemThree = Application.ActiveExplorer.Selection(1)
Set MyItemThree = MyItemTwo.Forward
Set MyItemFour = Application.ActiveExplorer.Selection(1)
Set MyItemFour = MyItemTwo.Forward
Set MyItemFive = Application.ActiveExplorer.Selection(1)
Set MyItemFive = MyItemTwo.Forward
Set MyItemSix = Application.ActiveExplorer.Selection(1)
Set MyItemSix = MyItemTwo.Forward
'Section 5
If olItem.Attachments.Count > 0 Then
For Each olAttach In olItem.Attachments
If Right(LCase(olAttach.FileName), 3) = "xls" Or Right(LCase(olAttach.FileName), 4) = "xlsx" Or Right(LCase(olAttach.FileName), 4) = "xlsm" Then 'Define the file types to search in
strFilename = strPath & Format(olItem.ReceivedTime, "yyyymmdd-HHMMSS") & _
Chr(32) & olAttach.FileName
olAttach.SaveAsFile strFilename
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to read the data
Set xlWB = xlApp.Workbooks.Open(strFilename)
Set xlSheet = xlWB.Sheets("Sheet1")
'Section 6
'A new xlSheet cell selection and If statement is required for mutually exclusive recipients as below. Multiple addresses can be added to one condition
If xlSheet.Range("A1").Value = "Enter_Value_To_Find" Then
MyItem.Recipients.Add "Enter_E-Mail_Address"
MyItem.Send
End If
If xlSheet.Range("B1").Value = "Enter_Value_To_Find" Then
MyItemTwo.Recipients.Add "Enter_E-Mail_Address"
MyItemTwo.Send
End If
If xlSheet.Range("F1").Value = "Enter_Value_To_Find" Then
MyItemThree.Recipients.Add "Enter_E-Mail_Address"
MyItemThree.Send
End If
If xlSheet.Range("C10").Value = "Enter_Value_To_Find" Then
MyItemFour.Recipients.Add "Enter_E-Mail_Address"
MyItemFour.Send
End If
If xlSheet.Range("D5").Value = "Enter_Value_To_Find" Then
MyItemFive.Recipients.Add "Enter_E-Mail_Address"
MyItemFive.Send
End If
If xlSheet.Range("E7").Value = "Enter_Value_To_Find" Then
MyItemSix.Recipients.Add "Enter_E-Mail_Addressa"
MyItemSix.Send
End If
'Section 7
xlWB.Close 0
If bXStarted Then xlApp.Quit
If Not bFound Then Kill strFilename
Exit For
End If
Next olAttach
End If
End Sub
Sub Test()
Dim olMsg As MailItem
On Error Resume Next
Set olMsg = ActiveExplorer.Selection.Item(1)
CheckAttachments olMsg
End Sub

Error Code 91 when trying to install on different machine

I've got an issue with some code when I've tried to install some code on a colleagues machine. The machine and version of Outlook are exactly the same and reference the same libraries. However, when I try and run the script on her machine, it throws up an error 91 on the 'Set xlWB = xlApp.Workbooks.Open(strPath)'.
The intention is to export necessary data from a selected email message into an Excel spreadsheet located in a specified directory.
Any clues as to what I should be trying in order to eliminate the error? First half of the code below.
Many thanks!
Option Explicit
Sub ServiceRequestTool()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim rCount As Long
Dim bXStarted As Boolean
Dim enviro As String
Dim strPath As String
Dim currentExplorer As Explorer
Dim Selection As Selection
Dim olItem As Outlook.MailItem
Dim obj As Object
Dim strColA, strColB, strColC As String
strPath = "H:\My Documents\General Docs\Govtnz-Service-Request.xlsm"
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
If Dir$("H:\My Documents\General Docs\Govtnz-Service-Request.xlsm") = "" Then
MsgBox "Contact the spreadsheet administrator for assistance.", vbOKOnly + vbCritical, "File not found!"
Exit Sub
End If
End If
On Error GoTo 0
Set xlWB = xlApp.Workbooks.Open(strPath)
Set xlSheet = xlWB.Sheets("requestAssignment")
On Error Resume Next
rCount = xlSheet.Range("C" & xlSheet.Rows.Count).End(-4162).Row + 1
Set currentExplorer = Application.ActiveExplorer
Set Selection = currentExplorer.Selection
For Each obj In Selection
Set olItem = obj
strColA = olItem.SenderName
strColB = olItem.SenderEmailAddress
strColC = olItem.ReceivedTime
xlSheet.Range("B" & rCount) = strColC
xlSheet.Range("C" & rCount) = strColA
xlSheet.Range("D" & rCount) = strColB
rCount = rCount + 1
Next
xlWB.Close 1
If bXStarted Then
xlApp.Quit
End If
Set olItem = Nothing
Set obj = Nothing
Set currentExplorer = Nothing
Set xlApp = Nothing
Set xlWB = Nothing
Set xlSheet = Nothing
End Sub
You are most probably getting that error because there is no instance of Excel which is running.
You need to create a new instance when GetObject doesn't find one.
You are checking for the existence of the file if Err <> 0? i.e when no Excel instance is found? That doesn't make sense. Check for the existence of the file first and then check for Excel.
Is this what you are trying? (untested)
Change your code
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
If Dir$("H:\My Documents\General Docs\Govtnz-Service-Request.xlsm") = "" Then
MsgBox "Contact the spreadsheet administrator for assistance.", _
vbOKOnly + vbCritical, "File not found!"
Exit Sub
End If
End If
On Error GoTo 0
to
'~~> Move ths out of that IF/EndIf
If Dir$("H:\My Documents\General Docs\Govtnz-Service-Request.xlsm") = "" Then
MsgBox "Contact the spreadsheet administrator for assistance.", _
vbOKOnly + vbCritical, "File not found!"
Exit Sub
End If
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Set xlApp = CreateObject("Excel.Application") '<~~ Add this line
End If
On Error GoTo 0
If xlApp Is Nothing Then
MsgBox "Excel is not installed"
Exit Sub
End If

Macro doesn't show in list

I want to export messages to Excel. However, when I try running the macro, I don't see it in the list.
I just copied the code below from http://www.slipstick.com/developer/vba-copy-outlook-email-excel-workbook
Option Explicit
Const xlUp As Long = -4162
Sub CopyToExcel(olItem As Outlook.MailItem)
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim rCount As Long
Dim bXStarted As Boolean
Dim strPath As String
Dim M1 As Object
Dim M As Object
Dim lgLastRow As Long 'specify the last data row
lgLastRow = Range("A1048576").End(xlUp).Row 'Take Note: very useful!!
enviro = CStr(Environ("username"))
'the path of the workbook
strPath = enviro & "C:\Desktop\Project\SR History File.xlsx"
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to input the data
Set xlWB = xlApp.Workbooks.Open(strPath)
Set xlSheet = xlWB.Sheets("Sheet1")
'Find the next empty line of the worksheet
rCount = lgLastRow = Range("A1048576").End(xlUp).Row + 1
xlSheet.Range("A" & rCount) = olItem.SentOn
xlSheet.Range("B" & rCount) = olItem.SenderEmailAddress
xlSheet.Range("C" & rCount) = olItem.Subject
xlWB.Close 1
If bXStarted Then
xlApp.Quit
End If
Set M = Nothing
Set M1 = Nothing
Set Reg1 = Nothing
Set xlApp = Nothing
Set xlWB = Nothing
Set xlSheet = Nothing
End Sub
The code cannot run without a parameter, olItem.
Open a mailitem then run this, which will be in the list.
Option Explicit
Sub CopyToExcel_Test
Dim currItem as mailitem
Set currItem = ActiveInspector.currentitem
CopyToExcel currItem
ExitRoutine:
Set currItem = Nothing
End Sub

Resources