0

I have a workbook that runs a query on SQL server and returns results. A macro then creates a customer facing copy and names it dynamically using values from the results and the date and saves it to the individual user's desktop.

If the macro is run a second time and this dynamically named file has been left open from the original run I get an error. How can I determine if the file is open from the earlier run and close it before starting the second run?

Sub CreateCustomerCopy()  
    ThisFile = ("Purchase History - Billing Acct# " & Range("A4").Value & " - " & Format(Date, "YYYYMMDD"))

    Range("A2:A2").Select
    Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
    Selection.Copy
    Workbooks.Add
    ActiveSheet.Paste

    'Save to Desktop of Variable User
    Dim strPath As String
    Dim Myar As Variant
    strPath = "C:\Users\username"
    Myar = Split(strPath, "\")
    Debug.Print CurDir & "\" & Myar(UBound(Myar))

    ActiveWorkbook.SaveAs Filename:="C:\Users\" & Myar(UBound(Myar)) & "\Desktop\" & ThisFile, _
      FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End Sub
Community
  • 1
  • 1
SeaFarmer
  • 25
  • 6

1 Answers1

0

Check to see if the workbook is open, and close it if it's open:

Dim wb As Workbook
On Error Resume Next
Set wb = Application.Workbooks.Item(ThisFile)
If (Not wb Is Nothing) Then wb.Close
Ken
  • 303
  • 1
  • 7