I am having trouble ending the Excel process that I call open with Outlook VBA.
I have looked into a few solutions like setting variables to Nothing at the end and using With statements after all variables.
The orphaned process seems to be causing problems when I call Excel over and over again.
The code is suppose to download the attachment, copy some cell values into a workbook, save and close the documents.
Private WithEvents myOlItems As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
Set myOlItems = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub myOlItems_ItemAdd(ByVal item As Object)
Dim Msg As Outlook.MailItem
Dim msgattach As Object
Dim wb As Workbook
Dim myXLApp As Excel.Application
Dim filepath As String
Dim filepathone As String
Dim filepathtwo As String
Dim wbhome As Worksheet
Dim comp As String
Dim wbtemp As Workbook
Dim testcode As Workbook
Dim matrix As Worksheet
Dim testflr As Worksheet
If TypeName(item) = "MailItem" Then
Set Msg = item
If Left(Msg.Subject, 14) = "SES Gas Matrix" Then
Set myXLApp = CreateObject("Excel.Application")
myXLApp.DisplayAlerts = False
If Msg.Attachments.Count <> 0 Then
For Each msgattach In Msg.Attachments
If Right(msgattach.FileName, 5) = ".xlsx" Then
filepath = "G:\Betts\Floor Matricies\FIFOs\" & Format(Now(), "YYYYMMDD") & " - " & "Gas Rates" & Right(msgattach.FileName, 5)
msgattach.SaveAsFile filepath
End If
Next
End If
Set msgattach = Nothing
Set wbtemp = Workbooks.Open(filepath, UpdateLinks:=3)
Set matrix = wbtemp.Sheets("Sheet1")
wbtemp.Activate
filepathtwo = Left(filepath, Len(filepath) - 5)
matrix.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
filepathtwo & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
filepathone = "http://intranet/Pricing%20and%20Rates/Floor%20Matrices/FIFOs/" & Format(Now(), "YYYYMMDD") & "%20-%20Gas%20Rates.pdf"
matrix.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
filepathone _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
Dim rangeb5l9 As Range
Set rangeb5l9 = matrix.Range("B5:L9")
rangeb5l9.Copy
Set rangeb5l9 = Nothing
On Error GoTo ErrorHandler
Set testcode = Workbooks.Open(FileName:="G:\Betts\ReturnOnInvestment_Master_Backup Testcode.xlsm", UpdateLinks:=3)
Set testflr = testcode.Sheets("Floor Pricing")
Dim rangea44 As Range
Dim rangeb93 As Range
Dim rangeb94 As Range
Set rangea44 = testflr.Range("A44")
rangea44.PasteSpecial xlPasteValues
myXLApp.CutCopyMode = False
Set rangea44 = Nothing
Set rangeb93 = testflr.Range("B93")
rangeb93 = "Yes"
wbtemp.Close
Set wbtemp = Nothing
Kill (filepath)
Set rangeb94 = testflr.Range("B94")
If rangeb93 = "Yes" And rangeb94 = "Yes" Then
testcode.Application.Run ("Module34.OFVT")
rangeb93 = "No"
rangeb94 = "No"
End If
Set rangeb94 = Nothing
Set rangeb93 = Nothing
Set testflr = Nothing
testcode.Close savechanges:=True
Set testcode = Nothing
Set matrix = Nothing
myXLApp.DisplayAlerts = True
myXLApp.Quit
Set myXLApp = Nothing
Msg.UnRead = False
End If
Set Msg = Nothing
End If
'test area
Set item = Nothing
Exit Sub
ErrorHandler:
If (Err.Number = 50290) Then Resume
Stop
Resume
End Sub
There are a few recommended rules that you could apply in this kind of applications.
1- Before opening Excel, check if Excel is already open and get the running instance. You can create a custom routine to do that:
Function getExcelApp() As Excel.Application
On Error Resume Next
Set getExcelApp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then Set getExcelApp = CreateObject("Excel.Application")
End Function
2- Make the application visible, at least in the phase where you're still writing and debugging your code.
Set myXLApp = getExcelApp ' <-- get it or create it
myXLApp .Visible = true ' <-- useful at least in the development phase
3- You can eventually shortcut the two-phases (create app, open doc) with just one step
Dim wb as Excel.Workbook
Set wb= GetObject(filepath)
This will either get an already open document instance or open it if not. You can later get the Application Object as wb.Application.
4- Make sure you correctly handle the error situations to that all paths will close the Excel application, including those resulting from an error.
5- Since the application you're using is temporary, keep it with DisplayAlerts = False state. As I see you reset it to DisplayAlerts = true before quitting. This is source of headache. Imagine the "non-visible" application blocked with some alert messagebox? I suggest you drop that line (keep false).
6- Qualify your ranges and object variables
Set wbtemp = myXlApp.Workbooks.Open(filepath, 3, True) '<-- better than using the unqualified Workbooks
Related
I have an excel workbook with multiple tabs and I created a Windows scheduled task to open the workbook and save the workbook to pdf however there is a error with this portion of the code when i debugged it. I think it may be the previous instance that had processed and left the same pdf in the same folder. It may not be overwritting the old pdf.
ERROR Run Time Error '-214701887 (80071779)'; Document not saved.
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=saveLocation
FULL VBA
Sub Auto_Open()
Dim sht As Worksheet
'AutoFit Every Worksheet Column in a Workbook
For Each sht In ThisWorkbook.Worksheets
sht.Cells.EntireColumn.AutoFit
Next sht
Application.DisplayAlerts = False
'Create and assign variables
Dim saveLocation As String
saveLocation = "C:\Users\manuel\Documents\SQL Server Management Studio\alert-email\LOG.PDF"
Application.DisplayAlerts = True
'Save active workbook as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=saveLocation
Dim OutLookApp As Object
Dim OutLookMailItem As Object
Dim myAtttachments As Object
Set OutLookApp = CreateObject("Outlook.Application")
Set OutLookMailItem = OutLookApp.CreateItem(0)
Set myAttachments = OutLookMailItem.Attachments
With OutLookMailItem
.To = "manuel#gmail.com"
.Subject = "Test Summary"
.Body = "This e-email is automatically generated and will be sent every weekday at 6AM. We can customerize and add more reports later."
myAttachments.Add "C:\Users\manuel\Documents\SQL Server Management Studio\alert-email\LOG.PDF"
.send
'.Display
End With
Set OutLookMailItem = Nothing
Set OutLookApp = Nothing
ThisWorkbook.Save
ThisWorkbook.Saved = True
Application.Quit
End Sub
Try this.
Option Explicit
Sub ExportXLToPDF()
'Comments:
'Assume list of worksheets to be included in output are listed in Column 1 on "List"
Dim wb As Workbook
Dim ws As Worksheet
Dim Arr() As String
Dim MaxRows As Long
Dim i As Long
Dim strPath As String
Dim strFileName As String
Const strEXTENSION As String = ".pdf"
Set wb = ThisWorkbook
Set ws = wb.Worksheets("List")
'User - where to save the output file
strPath = GetFolder & "\"
'User - what to name the output file
strFileName = GetUserInput(strPrompt:="Please enter a name for the output file", _
strTitle:="File Name")
'Assume list to be included in sheets array in on worksheet named list in Column 1 beginning in Row 1
'Total number of rows is dynamic
MaxRows = GetRows(ws:=ws)
'Redim the array to hold the name of the worksheets
ReDim Preserve Arr(1 To MaxRows)
'Load the list of sheets to be included into the array
For i = 1 To MaxRows
Arr(i) = ws.Cells(i, 1).Value
Next i
'Select the sheets array
Sheets(Arr).Select
'Export to the sheets array to pdf
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=strPath & strFileName & strEXTENSION, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'Tidy up
'Erase arrays
Erase Arr
'Destroy objects
Set ws = Nothing
Set wb = Nothing
End Sub
Public Function GetRows(ws As Worksheet) As Long
Dim r As Long
With ws
r = .Cells(Rows.Count, 1).End(xlUp).Row
GetRows = r
End With
End Function
Public Function GetUserInput(strPrompt As String, _
strTitle As String) As String
Dim strUserInput As String
strUserInput = InputBox(Prompt:=strPrompt, _
Title:=strTitle)
GetUserInput = strUserInput
End Function
Public Function GetFolder() As String
Dim fd As FileDialog
Dim strFolderName As String
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
With fd
.Title = "Please select a folder"
.AllowMultiSelect = False
.Show
strFolderName = .SelectedItems(1)
End With
GetFolder = strFolderName
Set fd = Nothing
End Function
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.
I have ContentControl drop down box in Word. Once I select an item from a Drop Down list I want to search for that in an Excel document and set the row number equal to a variable.
The code below is what I tried but the Columns("G:G").Find part says its not defined.
Sub findsomething(curRow)
Dim rng As Range
Dim rownumber As Long
curPath = ActiveDocument.path & "\"
Call Set_Variable(curPath)
StrWkShtNm = "Chapters"
If Dir(StrWkBkNm) = "" Then
MsgBox "Cannot find the designated workbook: " & StrWkBkNm, vbExclamation
Exit Sub
End If
Set rng = Columns("G:G").Find(what:=curRow)
rownumber = rng.Row
MsgBox rownumber
' Release Excel object memory
Set xlWkBk = Nothing
Set xlApp = Nothing
Application.ScreenUpdating = True
End Sub
While using more than one MS Office application it is a good idea to specify which application you are targeting:
Excel.Application.ThisWorkbook.Sheets(1).Range("A1").Select
this is what ended up working. you set me on the right track with referencing Excel.
Sub findsomething(curRow)
Dim rng As Long
Dim rownumber As Long
curPath = ActiveDocument.path & "\"
Call Set_Variable(curPath)
StrWkShtNm = "Chapters"
MsgBox "curRow = " & curRow
If Dir(StrWkBkNm) = "" Then
MsgBox "Cannot find the designated workbook: " & StrWkBkNm, vbExclamation
Exit Sub
End If
With xlApp
.Visible = False
Set xlWkBk = .Workbooks.Open(FileName:=StrWkBkNm, ReadOnly:=True, AddToMRU:=False)
With xlWkBk
With .Worksheets(StrWkShtNm)
rng = .Range("G:G").Find(what:=curRow)
MsgBox rng
End With
.Close False
End With
.Quit
End With
' Release Excel object memory
Set xlWkBk = Nothing: Set xlApp = Nothing
Application.ScreenUpdating = True
End Sub
I have a some command buttons that send access tables through to an excel spreadsheet and undergo some formatting and entering some formulas in them. The other command buttons work, but this one falls over at the LastRowInventory line.
I am sure its something to do with oBook but I can't quite figure out how to fix it. I think its because it is attempting to get an object it has already got. It runs smoothly every second time, but does not close the excel process. My attempts at resolving this over the last couple hours have not worked.
The error I have been getting is as follows:
Run-time error '462': The remote server machine does not exist or is unavailable
Any help is appreciated. I believe it is a simple fix but just can't quite get it, I'm pretty new to programming. The code is below.
Private Sub INVENTORYLIST_Click()
DTable = InputBox("Input Table Name")
'****************************TRANSFER TO EXCEL********************************
Dim strWorksheetPathTable As String
strWorksheetPathTable = "O:\GData\Downstream_LNG\Data Mgmt\CEDA\Reports\" & DTable & "\" & DTable & ".xls"
DoCmd.TransferSpreadsheet transfertype:=acExport, _
spreadsheettype:=acSpreadsheetTypeExcel12, _
TableName:=("" & DTable & "_INVENTORY LIST"), FileName:=strWorksheetPathTable, _
hasfieldnames:=True, _
Range:="InventoryList"
'****************************FORMAT INVENTORY SHEET***********************************
Dim xlApp As Object
Dim xlWB As Object
Set xlApp = CreateObject("Excel.Application")
Dim oBook As Excel.Workbook
Dim InventoryListSheet As Excel.Worksheet
Dim SummarySheet As Excel.Worksheet
Set xlWB = xlApp.Workbooks.Open("" & strWorksheetPathTable & "")
Set oBook = GetObject("" & strWorksheetPathTable & "")
Set InventoryListSheet = oBook.Sheets("InventoryList")
Set SummarySheet = oBook.Sheets("Summary")
With xlWB
With InventoryListSheet
'Some Spreadesheet Formatting in here
End With
End With
'****************************CREATE OE STATUS BREAKDOWN CALCULATIONS ON SUMMARY SHEET**********************
Dim LastRowInventory As Long
LastRowInventory = oBook.Sheets("InventoryList").Range("A" & Rows.Count & "").End(xlUp).Row
With xlWB
With SummarySheet
'Some Spreadsheet Formulas here
End With
End With
'*********************************ORDER WORKSHEETS*************************************
With xlWB
.Sheets("InventoryList").Select
.Sheets("InventoryList").Move Before:=oBook.Sheets(1)
.Sheets("Summary").Select
.Sheets("Summary").Move Before:=oBook.Sheets(1)
End With
If Not SummarySheet Is Nothing Then
Set SummarySheet = Nothing
End If
If Not InventoryListSheet Is Nothing Then
Set InventoryListSheet = Nothing
End If
If Not oBook Is Nothing Then
Set oBook = Nothing
End If
If Not xlWB Is Nothing Then
xlWB.Save
xlWB.Close
Set xlWB = Nothing
End If
If Not xlApp Is Nothing Then
xlApp.Quit
Set xlApp = Nothing
End If
DoCmd.SetWarnings True
MsgBox ("INVENTORY SHEET HAS BEEN CREATED.")
End Sub
Try this:
LastRowInventory = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row
Or if that doesn't work try:
LastRowInventory = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
Does this help you?
EDIT:
LastRowInventory = InventoryListSheet.Range("A" & InventoryListSheet.Rows.Count & "").End(xlUp).Row
By specifying the sheet that the rows are to be counted on the issue is fixed.
I am using VBA with an event listener on a specific sub-folder to run a macro when that folder receives an email. It is working perfectly, with one exception. I am setting the objects to listen, but they are getting set back to 'nothing' seemingly randomly, which stops the listeners from 'listening'. Here's the code I am using to set the listeners and trigger the macros:
Public WithEvents myOLItems As Outlook.Folder
Public WithEvents myTDLoanEmails As Outlook.Items
Private Sub Application_Startup()
Set myOLItems = Outlook.Session.GetDefaultFolder(olFolderInbox)
Set myTDLoanEmails = myOLItems.Folders("Trust Loan Collateral Tracking Text Files").Items
End Sub
Private Sub myTDLoanEmails_ItemAdd(ByVal Item As Object)
Call getAttachments
Call runTextToExcel
End Sub
'runTextToExcel' creates an Excel application, opens an Excel file, runs a macro in that file, and then closes the file and the application. I think the error may be stemming from the file/Excel application not closing completely, because if I run the Outlook macro again immediately after completion, it cannot find the Excel file, despite the fact that hasn't moved. This causes an error, which I think may be 'unsetting' the listeners. Is this possible?
If it helps (or you're curious) here are the two subs that are called above:
Private Sub runTextToExcel()
Dim xlApp As Object
Dim oWbk As Workbook
Dim TextToExcelFile As Workbook
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
End With
sFile = "Loan Text Files to Excel Converter_v004.xlsm"
sPath = "K:\Shared\Text to Excel\"
bOpened = False
For Each oWbk In Workbooks
If oWbk.Name = sFile Then bOpened = True
Next oWbk
If bOpened = False Then Workbooks.Open (sPath & sFile)
xlApp.Run "'" & sFile & "'!LoanTextFilesToExcel"
xlApp.DisplayAlerts = False
Workbooks(sFile).Close (True)
xlApp.DisplayAlerts = True
xlApp.Quit
End Sub
Private Sub getAttachments()
On Error GoTo GetAttachments_err
Dim ns As NameSpace
Dim Inbox As MAPIFolder
Dim TDLoanEmails As MAPIFolder
Dim Item As Object
Dim Atmt As Attachment
Dim FileName As String
Dim i As Integer
Set ns = GetNamespace("MAPI")
Set Inbox = ns.GetDefaultFolder(olFolderInbox)
Set TDLoanEmails = Inbox.Folders("Trust Loan Collateral Tracking Text Files")
For Each Item In TDLoanEmails.Items
If Item.Attachments.Count > 3 Then
If Day(Item.ReceivedTime) = Day(Date) And Month(Item.ReceivedTime) = Month(Date) And Year(Item.ReceivedTime) = Year(Date) Then
For Each Atmt In Item.Attachments
If Right(Atmt.FileName, 4) = ".TXT" Then
FileName = "K:\Shared\Text to Excel\Text Files\" & Left(Atmt.FileName, Len(Atmt.FileName) - 4) & "-" & Format(Date, "mmddyyyy") & ".txt"
Atmt.SaveAsFile FileName
End If
Next Atmt
End If
End If
Next Item
GetAttachments_exit:
Set Atmt = Nothing
Set Item = Nothing
Set ns = Nothing
Exit Sub
GetAttachments_err:
MsgBox "An unexpected error has occurred." _
& vbCrLf & "Please note and report the following information." _
& vbCrLf & "Macro Name: GetAttachments" _
& vbCrLf & "Error Number: " & Err.Number _
& vbCrLf & "Error Description: " & Err.Description _
, vbCritical, "Error!"
Resume GetAttachments_exit
End Sub
Thanks!
Not sure if it is because of the runTextToExcel But take a backup of your existing runTextToExcel and replace it with this.
I believe you are using Late Binding
Changes made in this code
Object Declared
Object Closed and Released properly
Code
Private Sub runTextToExcel()
Dim xlApp As Object
Dim oWbk As Object, wb As Object
Dim TextToExcelFile As Object '<~~ Are you using this anywhere?
Dim bOpened As Boolean
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
End With
sFile = "Loan Text Files to Excel Converter_v004.xlsm"
sPath = "K:\Shared\Text to Excel\"
bOpened = False
For Each oWbk In xlApp.Workbooks
If oWbk.Name = sFile Then bOpened = True
Next oWbk
If bOpened = False Then Set wb = xlApp.Workbooks.Open(sPath & sFile)
xlApp.Run "'" & sFile & "'!LoanTextFilesToExcel"
xlApp.DisplayAlerts = False
wb.Close (True)
xlApp.DisplayAlerts = True
xlApp.Quit
Set wb = Nothing
Set xlApp = Nothing
End Sub