I have created an Outlook macro that copies Outlook mails to an Excel sheet.
When the target workbook is already opened, the macro doesn't give expected results. I would like to close the already opened workbook.
I know how to do that using Excel VBA but how to deal with this using Outlook VBA.
I am using following code to check whether an Excel sheet is open.
Kindly note that I want to close the open workbook using Outlook VBA.
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Updates - 1 (Code I am using to open & populate the workbook)
Dim xlWB As Object
Dim xlSheet As Object
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
Set xlWB = xlApp.workbooks.Open(xlPath)
Set xlSheet = xlWB.sheets("output")
NextRow = xlSheet.Range("A" & xlApp.Rows.Count).End(3).Row + 1
With xlSheet
.cells(NextRow, "A") = Item.Subject
.cells(NextRow, "B") = Item.ReceivedTime
.cells(NextRow, "C") = xAsset
.cells(NextRow, "D") = Item.SenderName
.cells(NextRow, "E") = Item.SenderEmailAddress
End With
xlWB.Save
xlWB.Close SaveChanges:=True
xlApp.Quit
Set xlApp = Nothing
Set xlWB = Nothing
Set xlSheet = Nothing
Updates - 2 (Solution)
Dim wb As Object
Set wb = GetObject("C:\book1.xlsx")
If Not wb is Nothing then wb.close