views:

425

answers:

3

I am looking to export a few files into Excel from MS Access based on querying a table.

It's like this the query will be

select * from table where field = 0

I would like to loop the query till field is 9 and I want to save each result in a different name like field1, field2

How will this have to be modified?

strqry = "select * from table where field = 1"
DoCmd.TransferSpreadsheet acExport, _
                            acSpreadsheetTypeExcel9, _
                            "strqry", _
                            "C:\Reports\Data_Analysis1.xls", _
                            True

Also how do I name the first sheet as field1 and in next loop field2

+1  A: 

Speicify the sheet name in the "Range" field of the TransferSpreadsheet Command.

DoCmd.TransferSpreadsheet acExport, _
                            acSpreadsheetTypeExcel9, _
                            "tablename", _
                            "filename.xls", _
                            True, _
                            "sheetname"
Jason Lepack
+2  A: 

So really what you want is something like this

dim i as integer

for i = 1 to 9 
    strqry = "select * from table where field = "  & i
    DoCmd.TransferSpreadsheet acExport, _
                              acSpreadsheetTypeExcel9, _
                              strqry, _
                              "filename.xls", _
                              True, _
                              "sheetname_" & i
next i
CodeSlave
:D You copied my TransferSpredsheet line. ;)
Jason Lepack
But with this the results of query will not be exported right? i mean the table name given in docmd will be exported. But where is the query getting executed.I am sorry if i am missing something
tksy
@Jason - Yes. Just think of it as embracing and extending.
CodeSlave
@tksy, You are right, it should have been strqry, not "tablename". I've corrected it now.
CodeSlave
+2  A: 

I finally got it done this way

For i = 1 To 9
    CurrentDb.QueryDefs("MyQuery").SQL = "Select * from table Where field = " & i
    DoCmd.TransferSpreadsheet acExport, _
                                acSpreadsheetTypeExcel9, _
                                "MyQuery", _
                                "C:\Reports\Data_Analysis.xls", _
                                True, _
                                "Field_" & i
Next i
tksy
I'm glad you found something that worked. The negative about doing it this way is you end up updating a query object on the fly. If it's only used in one place that's OK-ish, but if it's used somewhere else, it's very confusing for later developers (especially if they update the query I the designer, and later find that it has been reverted to its original state again). Been there, done that.
CodeSlave