How can I run an Excel macro from an Outlook macro?
You will need to add the Microsoft Excel 14.0 Data Objects library. Go to Tools -> References.
You will also need to open the workbook before you can run a macro from it.
This should work:
Dim ExApp As Excel.Application
Dim ExWbk As Workbook
Set ExApp = New Excel.Application
Set ExWbk = ExApp.Workbooks.Open("C:\Folder\Folder\File.xls")
ExApp.Visible = True
ExWbk.Application.Run "ModuleName.YourMacro"
ExWbk.Close SaveChanges:=True
If you want to run this macro in the background and not open a visible instance of Excel, then set ExApp.Visible to False.
I just wanted to share how I do this. It doesn't apply to OP's needs, but the title may lead others here for more what I'm sharing. This will (optionally filter by sender/subject) save/open/run macro from spreadsheet received in outlook. I then have a macro in excel sometimes which sends notification/response etc, but I don't do this from Outlook (probably could though!).
Create a VBS script which will launch the excel file and run a macro (optionally the macro can be stored in a separate spreadsheet.)
"runmacro.vbs"
Set args = Wscript.Arguments
ws = WScript.Arguments.Item(0)
macro = WScript.Arguments.Item(1)
If wscript.arguments.count > 2 Then
macrowb = WScript.Arguments.Item(2)
End If
LaunchMacro
Sub LaunchMacro()
Dim xl
Dim xlBook
Set xl = CreateObject("Excel.application")
Set xlBook = xl.Workbooks.Open(ws, 0, True)
If wscript.arguments.count > 2 Then
Set macrowb = xl.Workbooks.Open(macrowb, 0, True)
End If
'xl.Application.Visible = True ' Show Excel Window
xl.Application.run macro
'xl.DisplayAlerts = False ' suppress prompts and alert messages while a macro is running
'xlBook.saved = True ' suppresses the Save Changes prompt when you close a workbook
'xl.activewindow.close
xl.Quit
End Sub
Outlook VBA Code (ThisOutlookSession):
https://www.slipstick.com/outlook/email/save-open-attachment/
Private Declare Function GetShortPathName Lib "kernel32" _
Alias "GetShortPathNameA" (ByVal lpszLongPath As String, _
ByVal lpszShortPath As String, ByVal cchBuffer As Long) As Long
Private Sub objItems_ItemAdd(ByVal Item As Object)
Dim objMail As Outlook.MailItem
Dim objWsShell As Object
Dim strTempFolder As String
Dim objAttachments As Outlook.Attachments
Dim objAttachment As Attachment
Dim strFileName As String
Dim Subject As String
Subject = Item.Subject
'If Subject Like "*SubTest*" Then
If Item.Class = olMail Then
Set objMail = Item
'Change sender email address
'If objMail.SenderEmailAddress = "boss#datanumen.com" Then
Set objWShell = CreateObject("WScript.Shell")
strTempFolder = Environ("Temp") & "\"
Set objWsShell = CreateObject("WScript.Shell")
Set objAttachments = objMail.Attachments
If objAttachments.Count > 0 Then
For Each objAttachment In objAttachments
strFileName = objAttachment.DisplayName
On Error Resume Next
Kill strTempFolder & strFileName
On Error GoTo 0
'Save the attachment
objAttachment.SaveAsFile strTempFolder & strFileName
'Open the attachment
vbs = (Chr(34) & "\\Server\Excel\" & "\runmacro.vbs " & Chr(34))
strFileName = GetShortFileName(strTempFolder & strFileName)
macro = "MacroName"
xlam = Environ("APPDATA") & "\Microsoft\Excel\XLSTART\Add-In.xlam"
On Error Resume Next
objWsShell.Run vbs & " " & strFileName & " " & macro & " " & xlam
objMail.UnRead = False
Next
'End If
End If
End If
'End If
End Sub
Function GetShortFileName(ByVal FullPath As String) As String
Dim lAns As Long
Dim sAns As String
Dim iLen As Integer
On Error Resume Next
If Dir(FullPath) <> "" Then
sAns = Space(255)
lAns = GetShortPathName(FullPath, sAns, 255)
GetShortFileName = Left(sAns, lAns)
End If
End Function
Related
I want to export data from selected Outlook emails to a workbook. Each email's data (subject, body, etc.) should be stored in a different worksheet.
I'm trying to edit this macro because it is almost what I need—and especially the part of olFormatHTML and WordEditor—because of split.
The idea is
Select multiple emails in Outlook
Open file path
Data for each email selected will be stored in a single worksheet from file opened
The issue with the macro is in this third part
From the selected items, the macro does a loop and just takes the first email selected,
The data is stored in different workbooks; it should be stored in the same workbook that I opened.
Public Sub SplitEmail()
Dim rpl As Outlook.MailItem
Dim itm As Object
Dim sPath As String, sFile As String
Dim objDoc As Word.Document
Dim txt As String
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim i As Long
Dim x As Long
'----------------------------
Dim myOlExp As Outlook.Explorer
Dim myOlSel As Outlook.Selection
Set myOlExp = Application.ActiveExplorer
Set myOlSel = myOlExp.Selection
For x = 1 To myOlSel.Count
'----------------------------------------------
Set itm = GetCurrentItem() 'A)I think the issuefrom selecting 1 item is located here
'|||||||||||||||||||||||||||||||||||||||||
sPath = "C:\Users\Ray\"
sFile = sPath & "Macro.xlsm"
If Not itm Is Nothing Then
Set rpl = itm.Reply
rpl.BodyFormat = olFormatHTML
'rpl.Display
End If
Set objDoc = rpl.GetInspector.WordEditor
txt = objDoc.Content.Text
'||||||||||||||||||||||||||||||||||||||||||||||
Set xlApp = CreateObject("Excel.application")
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(sFile) 'B) tried to move it to the beginning and macro doesn't work
'||||||||||||||||||||||||||||||||||||||||||||||
For i = LBound(Split(txt, Chr(13)), 1) To UBound(Split(txt, Chr(13)), 1)
wb.Worksheets(x).Range("A" & i + 1).Value = Split(txt, Chr(13))(i) 'B)emails in diferrent sheet but no same workbook
Next i
'------------------------------------------------------
Next x
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
End Select
GetCurrentItem.UnRead = False
Set objApp = Nothing
End Function
I made an update to this macro
as macro do loop in For x it open the file x times,
and then close it and open again instead of working on the first workbook opened
but the macro leaves open instances
here is the current code
Public Sub SplitEmail()
Dim rpl As Outlook.MailItem
Dim itm As Object
Dim sPath As String, sFile As String
Dim objDoc As Word.Document
Dim txt As String
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim i As Long
Dim x As Long
'----------------------------
Dim myOlExp As Outlook.Explorer
Dim myOlSel As Outlook.Selection
Set myOlExp = Application.ActiveExplorer
Set myOlSel = myOlExp.Selection
For x = 1 To myOlSel.Count
'----------------------------------------------
Dim objApp As Outlook.Application
Dim GetCurrentItem As Object
Set objApp = Application
On Error Resume Next
Select Case TypeName(objApp.ActiveWindow)
Case "Explorer"
Set GetCurrentItem = objApp.ActiveExplorer.Selection.item(x)
Case "Inspector"
Set GetCurrentItem = objApp.ActiveInspector.CurrentItem
End Select
GetCurrentItem.UnRead = False
Set objApp = Nothing
'-----------------------------------------------
Set itm = GetCurrentItem
sPath = "C:\Users\Ray\"
sFile = sPath & "Macro.xlsm"
If Not itm Is Nothing Then
'de lo contrario, se crea un Reply del correo en formato HTML
Set rpl = itm.Reply
rpl.BodyFormat = olFormatHTML
'rpl.Display
End If
Set objDoc = rpl.GetInspector.WordEditor
txt = objDoc.Content.Text
'||||||||||||||||||||||||||||||||||||||||||||||
Set xlApp = CreateObject("Excel.application")
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(sFile)
xlApp.Windows("Macro.xlsm").Activate
'Set wb = ActiveWorkbook
'||||||||||||||||||||||||||||||||||||||||||||||
For i = LBound(Split(txt, Chr(13)), 1) To UBound(Split(txt, Chr(13)), 1)
wb.Worksheets(x).Range("A" & i + 1).Value = Split(txt, Chr(13))(i)
Next i
xlApp.Windows("Macro.xlsm").Close SaveChanges:=True
xlApp.Workbook.Close SaveChanges:=False
'------------------------------------------------------
Next x
'------------------------------------------------------
'the instances should closed but not working, instances are empty
For Each wb In xlApp
wb.Close SaveChanges:=False
Next
End Sub
done, I added xlApp.Quit after saving files and deleted the last part For Each wb In xlApp...
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
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
I'm trying to write a macro in Outlook that reads an Excel file that has full paths and filenames in separate cells and inserts them as hyperlinks in an email.
I found information on how to create a hyperlink in Outlook. I can't find anything on how I Outlook would get the file paths from the Excel sheet.
Error says
Compile Error: User-defined type not defined
Sub links()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim ExcelFileName As String
Dim FilePath As String
ExcelFileName = "C:\links.xlsx"
Set exWb = objExcel.Workbooks.Open(ExcelFileName)
FilePath = exWb.Sheets("Sheet1").Cells(1, 1)
oMsg.TextBody = Chr(34) & FilePath & Chr(34)
End Sub
In the Outlook VBA editor set a reference to Excel.
Tools | References
Tick Microsoft Excel Object Library
Add Option Explict to new modules. You will find this helpful.
Tools | Options | Editor tab
Tick Require Variable Declaration
.
Option Explicit
Sub links()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim ExcelFileName As String
Dim FilePath As String
Dim oMsg As mailItem
ExcelFileName = "C:\links.xlsx"
Set exWb = objExcel.Workbooks.Open(ExcelFileName)
FilePath = exWb.Sheets("Sheet1").Cells(1, 1)
On Error Resume Next
Set oMsg = ActiveInspector.currentItem
On Error GoTo 0
If oMsg Is Nothing Then
Set oMsg = CreateItem(0)
oMsg.Display
End If
' This adds to existing text.
' Must display first to save a signature
'oMsg.body = Chr(34) & FilePath & Chr(34) & oMsg.body
'or
oMsg.HTMLBody = Chr(34) & FilePath & Chr(34) & oMsg.HTMLBody
ExitRoutine:
Set oMsg = Nothing
Set exWb = Nothing
Set objExcel = Nothing
End Sub
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