Create excel file when another excel file are open.

Hi Experts

I'm using this command to create an excel file:

DoCmd.DeleteObject acQuery, varQuery
Set varQryDef = CurrentDb.CreateQueryDef(varQuery, varSQL)

DoCmd.OpenQuery varQuery, acViewNormal, acReadOnly
If DCount("*", varQuery) > 0 Then
    DoCmd.RunCommand acCmdOutputToExcel
    varExcelCreated = True
End If

DoCmd.Close acQuery, varQuery

Set myXL = GetObject(, "Excel.Application")
Set xlBook = myXL.ActiveWorkbook
Set xlSheet = xlBook.Worksheets(1)

Is it a problem if another instance of excel are open while doing this?
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Using GetObject will try to find the existing excel instance. Why dont you just create a new excel object instead?
Also, you could just specify a file as    

Set myXL = CreateObject("Excel.Application")
Set xlBook = objExcel.Workbooks.Open(FileName:="c:\myfile.xls")

Or you can create a new excel workbook and paste the query results in there


    Dim objRecSet As DAO.Recordset
    Dim objExcel As Excel.Workbook
    Dim sSql As String
    sSql = "my query goes here - kinda like your varSQL"

    'Assign query results to a recordset    
    Set objRecSet = CurrentDb.OpenRecordset(sSql)

    'Open exce
    Set objExcel = CreateObject("Excel.Application")
    'On sheet 1, from A1, paste the results of the query
    objExcel.Sheets("1").Range("A1").CopyFromRecordset objRecSet

     'Save and get outta here
    Set objExcel = Nothing
    Set objRecSet = Nothing


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial

I always prefer to use  DoCmd.OutputTo acOutputQuery, not opening the Excel .
and then to use Set myXL = New Excel.Application etc & open the Excel.

Good Luck!

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Access

From novice to tech pro — start learning today.