Export queries to excel with Query name as the header

no not a problem thats fine. thank you for looking into it.. i am still trying to make it work as well (without any luck at this point)...i think i am going to put it down as well and start with freash mind tomorrow... :) thank you once again
 
Still having issues, hopefully you have a better idea Bob.
thanks!
 
ok so i've searched many fourms and still no clue as to how to print the query name or the checkbox label to row 1 in excel for each of the tabs. any help is appreciated it !
 
Hi John,
if i have more then one query then do i have to repeat these lines of code for each query?

Hi,

This is a snippit of code that I have for my export to excel, the code forces a insert first row, and then inserts the information I want in the first cell of the first column. It should give you something to work with:

Code:
[COLOR=blue]Set[/COLOR] objsheet = ObjExcel.ActiveWorkbook.Worksheets(1) [COLOR=green]'Set the objsheet to active worksheet in the active workbook[/COLOR]
    [COLOR=blue]With[/COLOR] objsheet  [COLOR=green]'With the active worksheet[/COLOR]
        .Rows("1:1").Font.Bold = [COLOR=blue]True[/COLOR] [COLOR=green]'Set the first row font to bold[/COLOR]
        .Rows("1:1").Font.Underline = xlUnderlineStyleSingle    [COLOR=green]'U[/COLOR][COLOR=green]nderline [/COLOR][COLOR=green]the text in each cell of the first row[/COLOR]
        .Rows("1:1").Select  [COLOR=green]'Insert a new row[/COLOR]
        ObjExcel.Selection.Insert Shift:=xlDown
            ObjExcel.Range("A1").Select [COLOR=green]'Select Cell A1[/COLOR]
            ObjExcel.ActiveCell.FormulaR1C1 = "[COLOR=red]Sky[/COLOR]"  [COLOR=green]'Assign the text "Sky [COLOR=red]This is where your query name would go[/COLOR]" to this cell
[/COLOR]           ObjExcel.Range("B1").Select  [COLOR=green]'Select Cell B1[/COLOR]
            ObjExcel.ActiveCell.FormulaR1C1 = "As At Date :"    [COLOR=green]'Assign [/COLOR][COLOR=green]the text "Date:" to this cell[/COLOR]
            ObjExcel.Range("D1").Select [COLOR=green]'Select Cell D1[/COLOR]
        ObjExcel.Selection.NumberFormat = "@"
        [COLOR=blue]With[/COLOR] ObjExcel.Selection
            .HorizontalAlignment = xlLeft [COLOR=green]'Left align the text[/COLOR]
            .VerticalAlignment = xlBottom [COLOR=green]'Bottom align the text[/COLOR]
            .ReadingOrder = xlContext
        [COLOR=blue]End With[/COLOR]

I hope this helps.

John
 
Hi,

In short in the way that I have this code working, Yes you would. My process is based on the fact that I know the exact number of queries and that for the present they will never exceed that number and therefore I have created a process that specifically targets each one in turn and exports the information as I want it.

Your process sounds very much dynamic in that as far as I understand you do not know the number of queries you will want to export at any given time and therefore targetting only those queries that meet your criteria at any given time will require more in depth programming than I am able to assist you with. I'm a mere beginner compared to some of the more seasoned and knowledgeable members of this forum.

John
 
you are much better then me for sure so don’t sell yourself short John! all in all thank you for your response and assistance! Hopefully i'll get this to work one way or another! thank you once again!
 
What I would do is to copy this code from my website (which I modified for you) and put it in a STANDARD MODULE and then name the module basExcel.

Code:
Public Function SendTQ2ExcelNameNewSheet(strTQName As String, strSheetName As String, Optional strFileName As String)
' strTQName is the name of the table or query you want to send to Excel
' strSheetName is the name of the sheet you want to name your sheet to

    Dim rst As DAO.Recordset
    Dim ApXL As Object
    Dim xlWBk As Object    
    Dim xlWSh As Object
    Dim fld As DAO.Field
    Dim wks As Object
    Dim strPath As String
 
    Const xlCenter As Long = -4108
    Const xlBottom As Long = -4107
 
    On Error GoTo Errors
    
    Set rst = CurrentDb.OpenRecordset(strTQName)
    Set ApXL = CreateObject("Excel.Application")

    If Dir(strFileName) <> vbNullString Then
        Set xlWBk = ApXL.Workbooks.Open(strFileName)
    Else
        Set xlWBk = ApXL.Workbooks.Add
    End If

    ApXL.Visible = True

    Set xlWSh = xlWBk.Worksheets.Add

    xlWSh.Name = strSheetName

    xlWSh.Range("A1").Select
 
    For Each fld In rst.Fields
        ApXL.ActiveCell = fld.Name
        ApXL.ActiveCell.Offset(0, 1).Select
    Next
 
    rst.MoveFirst

    xlWSh.Range("A2").CopyFromRecordset rst

    xlWSh.Range("1:1").Select

    ' This is included to show some of what you can do about formatting.  You can comment out or delete
    ' any of this that you don't want to use in your own export.
    With ApXL.Selection.Font
        .Name = "Arial"
        .Size = 12
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
    End With
    ApXL.Selection.Font.Bold = True
    With ApXL.Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .MergeCells = False
    End With

    ' selects all of the cells
    ApXL.ActiveSheet.Cells.Select

    ' does the "autofit" for all columns
    ApXL.ActiveSheet.Cells.EntireColumn.AutoFit

    ' selects the first cell to unselect all cells
    xlWSh.Range("A1").Select
 
    xlWSh.Range("A1").EntireRow.Insert
    xlWSh.Range("A1").Value = strTQName


    If strFileName <> vbNullString Then
        If Dir(strFileName) = vbNullString Then
            xlWBk.SaveAs strFileName
        Else
            xlWBk.Save
        End If
        xlWBk.Close False
    End If

    ApXL.Quit

    Set ApXL = Nothing

    rst.Close

    Set rst = Nothing
  

ExitHere:
    Exit Function
Errors:
    MsgBox "Error " & Err.Number & " -  Line # " & Erl & " - " & " (" & Err.Description & ") in procedure SendTQ2ExcelNameNewSheet of Module basExcel", , CurrentDb.Properties("AppTitle")
    Resume ExitHere
    Resume
End Function

And then you I would have a naming convention of the queries which would include this at the end
_r

And then I would call them all by using this type of method:

Code:
Dim qdf As DAO.QueryDef
Dim db As DAO.Database
 
For Each qdf In db.QueryDefs
   If Right(qdf.Name, 2) = "_r" Then
      SendTQ2ExcelNameNewSheet qdf.Name, Left(qdf.Name, 31), "C:\PathAndFileNameHere.xls"
   End If
Next
 
thank you Bob. this is working however it first pulls an excel file with some other result and then give me the error message once i click ok then it opens up the actual results that i want to see... so my question is how can i make the first spreadsheet that open to go away? and what does these line of codes mean?

If Dir(strFileName) <> vbNullString Then
'Kill (strFileName)
Set xlWBk = ApXL.Workbooks.Open(strFileName)
Else
Set xlWBk = ApXL.Workbooks.Add
End If


and


If strFileName <> vbNullString Then
If Dir(strFileName) = vbNullString Then
xlWBk.SaveAs strFileName
Else
xlWBk.Save
End If
xlWBk.Close False
End If
 
If Dir(strFileName) <> vbNullString

means that if the file exists then do that (open the file)

if it doesn't then create a new workbook.

But I did forget to mention that you would need to either delete the file if it exists in order for this to work or we will have to do some more modification so that if the sheet exists that it won't try to create it again but would instead clear it.

The last one is the same -

If the filename was passed to the function (as it is marked optional) then check to see if it exists and if it does then save and if it doesn't then do a save as.
 
i am still not getting why it opens the spreadsheet first with all the queries in a different form... then i would close out the spreadsheet, it asks if i want to save it, i would say no and then it brings me back to the DB where the error message comes in a pop up and then if i go back to my c drive the spreadsheet is there with all the queries and query names...

i have created a mini db of what i am trying to do and it will show you what i mean. I will send you via private message.

but thank you for what you have given me so far.
thanks!
 
I had that problem originally too for two reasons -

1. I had the File name wrong when I was testing (I had "C:Temp\MyTest.xls" and had forgotten the backslash after the C:. It was supposed to be C:\Temp\MyText.xls.

2. I also ran into a problem if there was a sheet already named the same as the query I was trying to use.
 
just realized i cant attach anything in the private message... at i couldnt figure it out...

from what i can tell the path nameis right and also i had deleted the spreadsheet so it doesnt seem like thats the issue

here is the mini DB...you'll have to select all checkboxes and then export, in my real DB it doesnt give me the runtime error (it highlights error message of the code and has the error as property not found) it does in this db so not sure whats happening here... but it still exports to c drive

but at least you'll see what i mean when i say it opens a spreadsheet and then gives me the error message and then its exported to C drive where the actual results are...

thanks again!
Summer
 

Attachments

Dang thing - this is doing what it was doing to me but the parts which made it do it for me are not appearing to be the problem. I will continue to troubleshoot but it may take a while.
 
Okay, here you go. I believe that the problem was that the folder didn't exist. So, I've implemented some code to account for that and I've done some other modifications which you will want to look at as well. I named the queries back to the original and removed the _r as I had forgotten you were going to use the checkboxes to select which you wanted. I have revised that click event extensively so you will want to take a look at that closely too.

So, let me know if it works for you. It currently does for me.
 

Attachments

thank you Bob. this is great!
if i want the excel to be visible when its done running then i know i have to put ApXL.Visible = Ture but would that be at the end of the code?
also one more question it puts the last query first when exported, is there a way to get the first query to discplay first and then in sequence of the checkboxes?
 
Actually it closes at the end so you would need to add something to open it up again. Do it in the click event and not the excel function.

There is a way to order the sheets. I can't tell you at the moment the code for that but I'm not sure the best way to tell it the order. I think maybe putting the names of the queries in a table with a sort order field so you can then use that after it is all done to iterate through and set which worksheets are in what order.
 

Users who are viewing this thread

Back
Top Bottom