{"id":738,"date":"2015-12-27T23:49:34","date_gmt":"2015-12-28T04:49:34","guid":{"rendered":"http:\/\/regina-whipp.com\/blog\/?p=738"},"modified":"2016-01-01T19:46:29","modified_gmt":"2016-01-02T00:46:29","slug":"send-to-excel","status":"publish","type":"post","link":"https:\/\/regina-whipp.com\/blog\/?p=738","title":{"rendered":"Export a Parameter Query to Excel&#8230;"},"content":{"rendered":"<p>It\u2019s always tricky when you want export filtered data to Excel.\u00a0 You will get an error message if you put try to put the Forms Control in the Criteria section of the Query.\u00a0 Why?\u00a0 Because Access insists on having the value before it can execute the export and not from the Form but directly in its SQL.\u00a0 So, we will create the Query *on the fly*, export and then delete it, after all, no need to keep it as it will be recreated with new parameters for the next export.\u00a0 Let\u2019s get started\u2026<\/p>\n<p>Create your Template (Line 17) and make note of which row you want your Recordset (data) to start on (Line 30), as well as, cells that you want to populate in the header part of your spreadsheet, such as, the date (Line 26).\u00a0 Then you will need the path of your Template and the path and naming convention of the saved worksheet (Line 43).<\/p>\n<p>Copy\/paste the <strong>Function SendToExcel<\/strong> into a Module\u2026 that said I usually put it behind the Filter Form because I am using a Template specific to a Recordset and I can use the same name for the Function and when I put the button on the Form I can keep that code the same, which a few minor changes.<\/p>\n<pre class=\"brush: vb; title: ; notranslate\" title=\"\">\r\nFunction SendToExcel(strTQName As String, strSheetName As String)\r\n'Modified from http:\/\/btabdevelopment.com\/export-a-table-or-query-to-excel-to-specific-worksheet\/\r\n' strTQName is the name of the table or query you want to send to Excel\r\n' strSheetName is the name of the sheet you want to send it to\r\n\r\n        Dim rst As DAO.Recordset\r\n        Dim ApXL As Object\r\n        Dim xlWBk As Object\r\n        Dim xlWSh As Object\r\n        Dim fld As DAO.Field\r\n        Dim lngMaxRow As Long\r\n        Dim lngMaxCol As Long\r\n        Dim strPath As String\r\n\r\n        On Error GoTo Err_Handler\r\n            'Full Path and Name of Template\r\n            strPath = &quot;Full Path and Name of Template&quot;\r\n\r\n            Set rst = CurrentDb.OpenRecordset(strTQName)\r\n            Set ApXL = CreateObject(&quot;Excel.Application&quot;)\r\n\r\n            Set xlWBk = ApXL.Workbooks.Open(strPath)\r\n            ApXL.Visible = True\r\n\r\n            'Set xlWSh = xlWBk.Worksheets(strSheetName)\r\n            'xlWSh.Range(&quot;A1&quot;).Value = Date\r\n\r\n            rst.MoveFirst\r\n           'The first row that you want your data to appear on\r\n            xlWSh.Range(&quot;A5&quot;).CopyFromRecordset rst\r\n            'Selects the first cell to unselect all cells\r\n            xlWSh.Range(&quot;A5&quot;).Select\r\n        'To apply Filters and to automatically resize the columns\r\n        xlWSh.Activate\r\n        xlWSh.Cells.Rows(4).AutoFilter\r\n        xlWSh.Cells.Rows(4).EntireColumn.AutoFit\r\n\r\n        rst.Close\r\n        Set rst = Nothing\r\n        'Remove prompts to save the Spreadsheet\r\n        ApXL.DisplayAlerts = False\r\n        'You will want to rename the Template so as to not overwrite it\r\n        xlWBk.SaveAs &quot;Full Path and Name of NEW Workbook&quot;, 51\r\n        ApXL.DisplayAlerts = True\r\n        'ApXL.Quit\r\n\r\n        Exit Function\r\nErr_Handler:\r\n        DoCmd.SetWarnings True\r\n        MsgBox Err.Description, vbExclamation, Err.Number\r\n        Exit Function\r\n\r\nEnd Function\r\n<\/pre>\n<p>Put a Command Button on your Form.\u00a0 Now, we need to determine what type of Query you have, is it&#8230;<\/p>\n<p><strong>Straight SQL<br \/>\n<\/strong><\/p>\n<pre class=\"brush: vb; title: ; notranslate\" title=\"\">\r\nstrSQL = &quot;SELECT... &quot; &amp; _\r\n         &quot;FROM...&quot;\r\n<\/pre>\n<p><strong>SQL with a Group By\u00a0<\/strong><\/p>\n<pre class=\"brush: vb; title: ; notranslate\" title=\"\">\r\nstrSQL = &quot;SELECT... &quot; &amp; _\r\n         &quot;FROM... &quot; &amp; _\r\n         &quot;GROUP BY...&quot;\r\n<\/pre>\n<p><strong>SQL with Criteria (WHERE) separate from what will be selected on the Form<\/strong><\/p>\n<pre class=\"brush: vb; title: ; notranslate\" title=\"\">\r\nstrSQL = &quot;SELECT... &quot; &amp; _\r\n         &quot;FROM... &quot; &amp; _\r\n         &quot;WHERE... &quot; &amp; _\r\n         &quot;ORDER BY...&quot;\r\n<\/pre>\n<p>Not sure?\u00a0 Go to Design View of the Query and then select SQL View (upper left hand corner).\u00a0 Once you got which one scroll down to the appropriate section.<\/p>\n<p>Then\u00a0copy\/paste the below between the <strong>Private Sub<\/strong> and <strong>End Sub<\/strong>.\u00a0 You will need to modify the filtering portion to match the name of the Controls and your Recordsource accordingly.\u00a0 Once done you can begin testing and adjusting.<\/p>\n<p><strong>Straight SQL<\/strong><\/p>\n<pre class=\"brush: vb; title: ; notranslate\" title=\"\">\r\n'Code from Allen Browne\u2019s site (http:\/\/allenbrowne.com\/ser-62code.html) modified\r\n\r\n        Dim dbs As DAO.Database\r\n        Dim qryDef As DAO.QueryDef\r\n        Dim strSQL As String\r\n        Dim strWhere As String\r\n        Dim lngLen As Long\r\n        Dim lngWhere As String\r\n\r\n        Set dbs = CurrentDb\r\n\r\n    'Put the SQL portion only of your Query here.\r\n    strSQL = &quot;SELECT\u2026\u201d\r\n\r\n    'Text field example. Use quotes around the value in the string.\r\n    If Not IsNull(Me.txtFilterCity) Then\r\n        strWhere = strWhere &amp; &quot;(&#x5B;City] = &quot;&quot;&quot; &amp; Me.txtFilterCity &amp; &quot;&quot;&quot;) AND &quot;\r\n    End If\r\n\r\n    'Another text field example. Use Like to find anywhere in the field.\r\n    If Not IsNull(Me.txtFilterMainName) Then\r\n        strWhere = strWhere &amp; &quot;(&#x5B;MainName] Like &quot;&quot;*&quot; &amp; Me.txtFilterMainName &amp; &quot;*&quot;&quot;) AND &quot;\r\n    End If\r\n\r\n    'Number field example. Do not add the extra quotes.\r\n    If Not IsNull(Me.cboFilterLevel) Then\r\n        strWhere = strWhere &amp; &quot;(&#x5B;LevelID] = &quot; &amp; Me.cboFilterLevel &amp; &quot;) AND &quot;\r\n    End If\r\n\r\n    'Yes\/No field and combo example. If combo is blank or contains &quot;ALL&quot;, we do nothing.\r\n    If Me.cboFilterIsCorporate = True Then\r\n        strWhere = strWhere &amp; &quot;(&#x5B;IsCorporate] = True) AND &quot;\r\n    ElseIf Me.cboFilterIsCorporate = 0 Then\r\n        strWhere = strWhere &amp; &quot;(&#x5B;IsCorporate] = False) AND &quot;\r\n    End If\r\n\r\n    'Date field example. Use the format string to add the # delimiters and get the right international format.\r\n    If Not IsNull(Me.txtStartDate) Then\r\n        strWhere = strWhere &amp; &quot;(&#x5B;EnteredOn] &gt;= &quot; &amp; Format(Me.txtStartDate, conJetDate) &amp; &quot;) AND &quot;\r\n    End If\r\n\r\n    'Another date field example. Use &quot;less than the next day&quot; since this field has times as well as dates.\r\n    If Not IsNull(Me.txtEndDate) Then   'Less than the next day.\r\n        strWhere = strWhere &amp; &quot;(&#x5B;EnteredOn] &lt; &quot; &amp; Format(Me.txtEndDate + 1, conJetDate) &amp; &quot;) AND &quot;\r\n    End If\r\n\r\n'I added an example for multi-select List Boxes\r\n        If Me.lstRoleID.ItemsSelected.Count &lt;&gt; 0 Then\r\n            'add selected values to string\r\n            Set ctl = Me.lstRoleID\r\n            For Each varItem In ctl.ItemsSelected\r\n              'strWhere = strWhere &amp; ctl.ItemData(varItem) &amp; &quot;,&quot;\r\n              'Use this line if your value is text\r\n              lngWhere = lngWhere &amp; &quot;'&quot; &amp; ctl.ItemData(varItem) &amp; &quot;',&quot;\r\n            Next varItem\r\n            'trim trailing comma\r\n            lngWhere = Left(lngWhere, Len(lngWhere) - 1)\r\n            strWhere = strWhere &amp; &quot;stSourceType IN(&quot; &amp; lngWhere &amp; &quot;) AND &quot;\r\n        End If\r\n\r\n    lngLen = Len(strWhere) - 5\r\n\r\n    If lngLen &lt;= 0 Then\r\n        'If no selection is made then send everything to Excel\r\n        strSQL = strSQL\r\n        Set qryDef = dbs.CreateQueryDef(&quot;qrySendToExcel&quot;, strSQL)\r\n        'DoCmd.OpenQuery qryDef.Name\r\n        qryDef.Close\r\n        Set qryDef = Nothing\r\n        DoEvents\r\n        Call SendToExcel(&quot;qrySendToExcel&quot;, &quot;Sheet1&quot;)\r\n        DoEvents\r\n        DoCmd.DeleteObject acQuery, &quot;qrySendToExcel&quot;\r\n    Else\r\n        'Send filtered results to Excel\r\n        strWhere = Left$(strWhere, lngLen)\r\n        strSQL = strSQL &amp; &quot; WHERE &quot; &amp; strWhere\r\n        Set qryDef = dbs.CreateQueryDef(&quot;qrySendToExcel&quot;, strSQL)\r\n        'DoCmd.OpenQuery qryDef.Name\r\n        qryDef.Close\r\n        Set qryDef = Nothing\r\n        DoEvents\r\n        Call SendToExcel(&quot;qrySendToExcel&quot;, &quot;Sheet1&quot;)\r\n        DoEvents\r\n        DoCmd.DeleteObject acQuery, &quot;qrySendToExcel&quot;\r\n    End If\r\n\r\n        dbs.Close\r\n        Set dbs = Nothing\r\n<\/pre>\n<p><strong>SQL with a Group By\u00a0 <\/strong>*You will need to add the filtering from Straight SQL<\/p>\n<pre class=\"brush: vb; title: ; notranslate\" title=\"\">\r\n        Dim dbs As DAO.Database\r\n        Dim qryDef As DAO.QueryDef\r\n        Dim strSQL As String\r\n        Dim strWhere As String\r\n        Dim strOrderBy As String\r\n        Dim lngLen As Long\r\n        Dim lngWhere As String\r\n\r\n        Set dbs = CurrentDb\r\n\r\n    'Put the SQL portion only of your Query here.\r\n    strSQL = &quot;SELECT\u2026\u201d\r\n\r\n    strOrderBy = &quot; ORDER BY quniMIForExcel.mySequence&quot;\r\n\r\n'ADD FILTERING FROM Straight SQL and adjust\r\n\r\n    lngLen = Len(strWhere) - 5\r\n\r\n    If lngLen &lt;= 0 Then\r\n        'If no selection is made then send everything to Excel\r\n        strSQL = strSQL &amp; strOrderBy\r\n        Set qryDef = dbs.CreateQueryDef(&quot;qrySendToExcel&quot;, strSQL)\r\n        'DoCmd.OpenQuery qryDef.Name\r\n        qryDef.Close\r\n        Set qryDef = Nothing\r\n        DoEvents\r\n        Call SendToExcel(&quot;qrySendToExcel&quot;, &quot;Sheet1&quot;)\r\n        DoEvents\r\n        DoCmd.DeleteObject acQuery, &quot;qrySendToExcel&quot;\r\n    Else\r\n        'Send filtered results to Excel\r\n        strWhere = Left$(strWhere, lngLen)\r\n        strSQL = strSQL &amp; &quot; WHERE &quot; &amp; strWhere &amp; strOrderBy\r\n        Set qryDef = dbs.CreateQueryDef(&quot;qrySendToExcel&quot;, strSQL)\r\n        'DoCmd.OpenQuery qryDef.Name\r\n        qryDef.Close\r\n        Set qryDef = Nothing\r\n        DoEvents\r\n        Call SendToExcel(&quot;qrySendToExcel &quot;, &quot;Sheet1&quot;)\r\n        DoEvents\r\n        DoCmd.DeleteObject acQuery, &quot;qrySendToExcel&quot;\r\n    End If\r\n\r\n        dbs.Close\r\n        Set dbs = Nothing\r\n<\/pre>\n<p><strong>SQL with Criteria separate from what will be selected on the Form\u00a0 <\/strong>*You will need to add the filtering from Straight SQL<\/p>\n<pre class=\"brush: vb; title: ; notranslate\" title=\"\">\r\n        Dim dbs As DAO.Database\r\n        Dim qryDef As DAO.QueryDef\r\n        Dim strSQL As String\r\n        Dim strWhere As String\r\n        Dim strQueryWhere As String\r\n        Dim strOrderBy As String\r\n        Dim lngLen As Long\r\n        Dim lngWhere As String\r\n\r\n        Set dbs = CurrentDb\r\n\r\n    'Put the SQL portion only of your Query here.\r\n    strSQL = &quot;SELECT\u2026\u201d\r\n\r\n    strOrderBy = &quot; ORDER BY quniMIForExcel.mySequence&quot;\r\n    strQueryWhere = &quot;(((tblLifts.lStatusID)=1 Or (tblLifts.lStatusID)=0) AND ((tblLifts.lTransferTo) Is Null) AND ((tblCoilRun.crNoShow)=False))&quot;\r\n\r\n'ADD FILTERING FROM Straight SQL and adjust\r\n\r\n    lngLen = Len(strWhere) - 5\r\n\r\n    If lngLen &lt;= 0 Then\r\n        'If no selection is made then send everything to Excel\r\n        strSQL = strSQL &amp; &quot; WHERE &quot; &amp; strQueryWhere &amp; strOrderBy\r\n        Set qryDef = dbs.CreateQueryDef(&quot;qrySendToExcel&quot;, strSQL)\r\n        'DoCmd.OpenQuery qryDef.Name\r\n        qryDef.Close\r\n        Set qryDef = Nothing\r\n        DoEvents\r\n        Call SendToExcel(&quot;qrySendToExcel&quot;, &quot;Sheet1&quot;)\r\n        DoEvents\r\n        DoCmd.DeleteObject acQuery, &quot;qrySendToExcel&quot;\r\n    Else\r\n        'Send filtered results to Excel\r\n        strWhere = Left$(strWhere, lngLen)\r\n        strSQL = strSQL &amp; &quot; WHERE &quot; &amp; strQueryWhere &amp; &quot; AND &quot; &amp; strWhere &amp; strOrderBy\r\n        Set qryDef = dbs.CreateQueryDef(&quot;qrySendToExcel&quot;, strSQL)\r\n        'DoCmd.OpenQuery qryDef.Name\r\n        qryDef.Close\r\n        Set qryDef = Nothing\r\n        DoEvents\r\n        Call SendToExcel(&quot;qrySendToExcel&quot;, &quot;Sheet1&quot;)\r\n        DoEvents\r\n        DoCmd.DeleteObject acQuery, &quot;qrySendToExcel&quot;\r\n    End If\r\n\r\n        dbs.Close\r\n        Set dbs = Nothing\r\n<\/pre>\n<p>Don&#8217;t forget to add error code!<\/p>\n<div class=\"pvc_clear\"><\/div>\n<p id=\"pvc_stats_738\" class=\"pvc_stats all  \" data-element-id=\"738\" style=\"\"><i class=\"pvc-stats-icon medium\" aria-hidden=\"true\"><svg aria-hidden=\"true\" focusable=\"false\" data-prefix=\"far\" data-icon=\"chart-bar\" role=\"img\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" viewBox=\"0 0 512 512\" class=\"svg-inline--fa fa-chart-bar fa-w-16 fa-2x\"><path fill=\"currentColor\" d=\"M396.8 352h22.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-192 0h22.4c6.4 0 12.8-6.4 12.8-12.8V140.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h22.4c6.4 0 12.8-6.4 12.8-12.8V204.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zM496 400H48V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16zm-387.2-48h22.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8z\" class=\"\"><\/path><\/svg><\/i> <img loading=\"lazy\" decoding=\"async\" width=\"16\" height=\"16\" alt=\"Loading\" src=\"https:\/\/regina-whipp.com\/blog\/wp-content\/plugins\/page-views-count\/ajax-loader-2x.gif\" border=0 \/><\/p>\n<div class=\"pvc_clear\"><\/div>\n","protected":false},"excerpt":{"rendered":"<p>It\u2019s always tricky when you want export filtered data to Excel. You will get an error message if you put try to put the Forms Control in the Criteria section of the Query. Why? Because Access insists on having the value before it can execute the export and not from the Form but directly in [&#8230;]<\/p>\n<div class=\"pvc_clear\"><\/div>\n<p id=\"pvc_stats_738\" class=\"pvc_stats all  \" data-element-id=\"738\" style=\"\"><i class=\"pvc-stats-icon medium\" aria-hidden=\"true\"><svg aria-hidden=\"true\" focusable=\"false\" data-prefix=\"far\" data-icon=\"chart-bar\" role=\"img\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" viewBox=\"0 0 512 512\" class=\"svg-inline--fa fa-chart-bar fa-w-16 fa-2x\"><path fill=\"currentColor\" d=\"M396.8 352h22.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-192 0h22.4c6.4 0 12.8-6.4 12.8-12.8V140.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h22.4c6.4 0 12.8-6.4 12.8-12.8V204.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zM496 400H48V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16zm-387.2-48h22.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8z\" class=\"\"><\/path><\/svg><\/i> <img loading=\"lazy\" decoding=\"async\" width=\"16\" height=\"16\" alt=\"Loading\" src=\"https:\/\/regina-whipp.com\/blog\/wp-content\/plugins\/page-views-count\/ajax-loader-2x.gif\" border=0 \/><\/p>\n<div class=\"pvc_clear\"><\/div>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5,63],"tags":[34,38,22,30,21],"class_list":["post-738","post","type-post","status-publish","format-standard","hentry","category-access-tips","category-database-design","tag-excel","tag-export","tag-queries","tag-reports","tag-vba","odd"],"_links":{"self":[{"href":"https:\/\/regina-whipp.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/738","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/regina-whipp.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/regina-whipp.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/regina-whipp.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/regina-whipp.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=738"}],"version-history":[{"count":15,"href":"https:\/\/regina-whipp.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/738\/revisions"}],"predecessor-version":[{"id":1179,"href":"https:\/\/regina-whipp.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/738\/revisions\/1179"}],"wp:attachment":[{"href":"https:\/\/regina-whipp.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=738"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/regina-whipp.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=738"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/regina-whipp.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=738"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}