Export queries to Excel - specific sheet, specific range

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • CarrieR
    New Member
    • Mar 2007
    • 21

    Export queries to Excel - specific sheet, specific range

    Hi,

    I thought this was a simple issue, but apparently it's not. I need to export the contents of about 30 queries, each into a specific sheet, and cell range, of an existing Excel workbook.

    Here are all of the details I need in one sample transfer:

    Query = "Query A"
    Excel workbook = "C:\Documen ts and Settings\All Users\Workbook1 .xlsx"
    Sheet = "BB DATA"
    Range = B2:J32
    HasFieldNames = True

    There are a lot of threads about exporting to Excel from Access, but I have searched all afternoon and can't find an answer that works. Sorry if I'm being a noob on this, but I just can't figure this one out.

    Thanks so much for any help
  • colintis
    Contributor
    • Mar 2010
    • 255

    #2
    Hi CarrieR,

    Had you tried using the DoCmd.TransferS preadsheet function?
    Code:
    Dim fileName As String
    fileName = "C:\Documents and Settings\All Users\Workbook1.xlsx"
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "Query A", fileName, True,"B2:J32"
    Here's something extra I work along with as well, creating the file name more dynamically. The code below will create the excel file in the same location where the database located, and the file is named with current date when executed.
    Code:
    fileName = Left(CurrentDb.Name, Len(CurrentDb.Name) - Len(Dir(CurrentDb.Name))) & "Report" & "-" & Format(Date, "yyyymmdd") & ".xlsx"
    The transferSpreads heet command would only be exporting the query to a new excel file, or replacing an existing file. So put this as a reference for creating a new file.
    Last edited by colintis; Nov 16 '10, 06:10 AM. Reason: Just leave a note at the end.

    Comment

    • CarrieR
      New Member
      • Mar 2007
      • 21

      #3
      Yes, the problem with the TransferSpreads heet command, unfortunately, is that it won't export to a specific sheet. This is a pretty vital need, since the spreadsheet is a (complex) template for a lot of reporting...

      Comment

      • colintis
        Contributor
        • Mar 2010
        • 255

        #4
        Sorry I maybe mis-understood the question. As you want to put the generated records into existing workbooks (excel files), here's a sample code on what I've done from my work.
        Code:
            Dim xlApp As Excel.Application
            Dim xlWB As Excel.Workbook
            Dim xlWS As Excel.Worksheet
            Dim acRng As Variant
            Dim xlRow As Integer
            
            Dim qry As QueryDef
            Dim rst As Recordset
            Set xlApp = New Excel.Application
            Set xlWB = xlApp.Workbooks.Open("C:\Documents and Settings\All Users\Workbook1.xlsx")
            Set xlWS = xlWB.Worksheets("BB Data")
            
            xlRow = (xlWS.Columns("A").End(xlDown).Row)
            
            Set qry = CurrentDb.QueryDefs("Query A")
            Set rst = qry.OpenRecordset
            
            Dim c As Integer
            c = 1
            xlRow = xlRow + 1
            
            Do Until rst.EOF
                For Each acRng In rst.Fields
                    xlWS.Cells(xlRow, c).Formula = acRng
                    c = c + 1
                Next acRng
                xlRow = xlRow + 1
                c = 1
                rst.MoveNext
                If xlRow > 25 Then GoTo rq_Exit
            Loop
            
        rq_Exit:
            rst.Close
            Set rst = Nothing
            Set xlWS = Nothing
            xlWB.Close acSaveYes
            Set xlWB = Nothing
            xlApp.Quit
            Set xlApp = Nothing
            Exit Function
        The code before at the end of loop is simply limiting the copy process only allow 25 records, so remove it as you like. In the end of the exit part, it is a good hand on having a .Close and .Quit, otherwise the excel won't close itself and you need to kill the process from Task manager.
        Last edited by colintis; Nov 16 '10, 06:14 AM. Reason: Add additional explanation on codes

        Comment

        • CarrieR
          New Member
          • Mar 2007
          • 21

          #5
          Thanks for your help!
          Sorry this response is a little late - I had to leave and come back to this particular problem for a while...

          Problem is solved (mostly, except for one or two small issues that I can work around).

          I did want to note the issues here, for others that might see this thread, or in case anyone wanted to respond.

          To note, I followed the above code exactly. To adjust the starting row the query would be exported to, I changed these lines:
          Code:
          Dim c As Integer
          c = 1
          xlRow = xlRow + 1
          the "x1Rox + 1" will insert the file data starting in Row 3. So to begin the data in Row 41, it would be changed to:
          Code:
          Dim c As Integer
          c = 1
          xlRow = xlRow + 39
          If I misunderstood any of this please let me know. These were the two issues I had:

          1. I couldn't adjust the column that the first record appeared in, even if I adjusted:
          Code:
          xlRow = (xlWS.Columns("A").End(xlDown).Row)
          to:
          Code:
          xlRow = (xlWS.Columns("B").End(xlDown).Row)
          Not sure if changing the first column can be done. To solve my issue, I just made sure all of my destinations began in column A, which worked out fine for this project.

          2. Export did not export the field names, only the data. Again, this was OK, but not sure if this is because I was doing something wrong.

          Comment

          • colintis
            Contributor
            • Mar 2010
            • 255

            #6
            Yes you did misunderstood the code you tried to modified.

            Code:
            Dim c As Integer
            c = 1
            xlRow = xlRow + 1
            xlRow simply record the row number of the 1st empty cell in your spreadsheet in column A. So if A3 is the first empty cell from top, then you will get 3 in xlRow+1, and therefore change the column from reading A to B is correct, if you are leaving column A for something else.

            The variable c is the one that stores column number, in which c = 1 means column A, c will be 2 for column B and so on.

            In part of the code I posted earlier.
            Code:
            xlWS.Cells(xlRow, c).Formula = acRng
            If xlRow+1 is 41, and c = 3, then the xlWS.Cells will be point to cell C41

            Comment

            • CarrieR
              New Member
              • Mar 2007
              • 21

              #7
              Thanks, I appreciate the clarification, and patience! This did exactly what I needed to do.

              Just to note:
              I changed the initial set of "xlRow = xlRow + 1" (the one before the loop) to simply set "xlRow = 3", or whatever row number I need for each of these I need to write. This worked perfectly.

              Thanks again for your help!

              Comment

              • colintis
                Contributor
                • Mar 2010
                • 255

                #8
                No worries =)

                As if you will be overwriting the information whenever you generate the data, then I do agree you use xlRow = 3, so that it will starts putting data from row 3 every time you execute the code.

                Comment

                • sarak
                  New Member
                  • Mar 2012
                  • 1

                  #9
                  hi,

                  I tried and this too works...

                  Code:
                  DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "Query A", fileName, True, "BB DATA!B2:J32"
                  change the range as required... may be for 6th row.. it may come like "BB DATA!A6:J32"
                  Last edited by NeoPa; Feb 20 '14, 04:03 AM. Reason: Added mandatory [CODE] tags

                  Comment

                  • hurude
                    New Member
                    • Feb 2014
                    • 1

                    #10
                    Hi, If you use a named range in your spreadsheet you can export directly to it, for example

                    On worksheet:
                    Create a named range for DATA A6:J32 = "Range1"

                    Code:
                    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "Query A", fileName, True, "Range1"
                    This will export directly to the correct sheets and range.
                    Last edited by NeoPa; Feb 20 '14, 04:04 AM. Reason: Added mandatory [CODE] tags

                    Comment

                    • dsatino
                      Contributor
                      • May 2010
                      • 393

                      #11
                      Just as a suggestion, you may look into doing it the other way around.

                      Excel can connect to a database and query it just as Access can.

                      Find Microsoft Excel help and learning resources. Explore how-to articles, guides, training videos, and tips to efficiently use Excel.

                      Comment

                      • zmbd
                        Recognized Expert Moderator Expert
                        • Mar 2012
                        • 5501

                        #12
                        hurude: Hi, If you use a named range in your spreadsheet you can export directly to it, for example (...)
                        Be advised, this is an "undocument ed" and therefore unsupported method. Reliance upon this method is discouraged as it may be removed, amended, or provide un-reliable results either now or in the future.

                        From Microsoft's website:
                        ----------
                        DoCmd.TransferS preadsheet Method (Access)Office 2010
                        Range
                        Optional
                        Variant
                        A string expression that's a valid range of cells or the name of a range in the spreadsheet. This argument applies only to importing. Leave this argument blank to import the entire spreadsheet. When you export to a spreadsheet, you must leave this argument blank. If you enter a range, the export will fail.
                        ----------

                        @hurude:
                        This method was already mentioned in Post#9
                        In the future, please carefully read the entire thread before posting to such an old thread. If dsatino had not already replied your post would simply have been removed as it covers old information.
                        Last edited by zmbd; Feb 19 '14, 08:01 PM.

                        Comment

                        Working...