0

I have a function that generates an HTML table from an SQL query string.

I want to get the current active report's query string with all my filters and generate an HTML table from that. Then, I can include it in my Outlook email.

I am trying to create a function that does the following:

  1. Opens up MS Outlook.
  2. Opens an already made template.
  3. Replaces a string in the template with the table generated from the currently active report.
  4. Add the currently active report as a PDF attachment.

Here is my code:

Option Compare Database
Option Explicit

Private Sub emailSupplier_Click()
    ' Define the parameters
    Dim objOutlook As Outlook.Application
    Dim objOutlookMsg As Outlook.MailItem
    Dim objOutlookRecip As Outlook.Recipient
    Dim objOutlookAttach As Outlook.Attachment
    Dim templateExpediter As String
    Dim msgBody As String
    Dim strFind As String
    Dim strNew As String
    Dim currentReport As Report
    Dim query As String

    ' Set the params
    Set currentReport = Screen.ActiveReport
    Set query = currentReport.RecordSource
    Set templateExpediter = "D:\Templates\expediter.oft"
    ' Create the Outlook session.
    Set objOutlook = CreateObject("Outlook.Application")
    ' Create the message.
    Set objOutlookMsg = objOutlook.CreateItemFromTemplate(templateExpediter)

    With objOutlookMsg
       ' Add the To recipient(s) to the message.
       Set objOutlookRecip = .Recipients.Add("firstmail")
       objOutlookRecip.Type = olTo

       ' Add the CC recipient(s) to the message.
       Set objOutlookRecip = .Recipients.Add("secondamail")
       objOutlookRecip.Type = olCC

       ' Set the Subject, Body, and Importance of the message.
       .BodyFormat = olFormatHTML
       .Subject = "Urgent Delivery Request - " & Date
       .Importance = olImportanceHigh 'High importance

       strFind = "{X}"
       ' Get HTML from the query for the record set
       strNew = GenHTMLTable(query)
       .HTMLBody = Replace(.HTMLBody, strFind, strNew)

       ' Resolve each Recipient's name.
       For Each objOutlookRecip In .Recipients
          objOutlookRecip.Resolve
       Next

       ' Should we display the message before sending?
       'If DisplayMsg Then
          '.Display
       'Else
          .Save
          .Display
       'End If

    End With
    Set objOutlook = Nothing

End Sub

My question is how can I convert my current active report recordsource or set, into an active HTML table?

Or at least get the SQL Query with filters so I can generate using the function QueryToHtmlTable(Query).

  • EDIT 2 - Ok, so i got the correct SQL with filters. Now it seems this function to generate HTML from the sql is giving me an error 'item is not found in collection'

    Function GenHTMLTable(sQuery As String, Optional bInclHeader As Boolean = True) As String
        On Error GoTo Error_Handler
        Dim db As DAO.Database
        Dim qdf As DAO.QueryDef
        Dim prm As DAO.Parameter
        Dim rs As DAO.Recordset
        Dim fld As DAO.Field
        Dim sHTML As String
    
        Set db = CurrentDb
        Set qdf = db.QueryDefs(sQuery)
    
        For Each prm In qdf.Parameters
            prm = Eval(prm.Name)
        Next prm
    
        Set rs = qdf.OpenRecordset
        With rs
            sHTML = "<table>" & vbCrLf
            If bInclHeader = True Then
                'Build the header row if requested
                sHTML = sHTML & vbTab & "<tr>" & vbCrLf
                For Each fld In rs.Fields
                    sHTML = sHTML & vbTab & vbTab & "<th>" & fld.Name & "</th>" & vbCrLf
                Next
                sHTML = sHTML & vbTab & "</tr>" & vbCrLf
            End If
            If .RecordCount <> 0 Then
                Do While Not .EOF
                    'Build a row for each record in the recordset
                    sHTML = sHTML & vbTab & "<tr>" & vbCrLf
                    For Each fld In rs.Fields
                        sHTML = sHTML & vbTab & vbTab & "<td>" & fld.Value & "</td>" & vbCrLf
                    Next
                    sHTML = sHTML & vbTab & "</tr>" & vbCrLf
                    .MoveNext
                Loop
            End If
            sHTML = sHTML & "</table>"
        End With
    
        GenHTMLTable = sHTML
    
    Error_Handler_Exit:
        On Error Resume Next
        If Not fld Is Nothing Then Set fld = Nothing
        If Not rs Is Nothing Then
            rs.Close
            Set rs = Nothing
        End If
        If Not db Is Nothing Then Set db = Nothing
        Exit Function
    
    Error_Handler:
        MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
               "Error Number: " & Err.Number & vbCrLf & _
               "Error Source: GenHTMLTable" & vbCrLf & _
               "Error Description: " & Err.Description & _
               Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
               , vbOKOnly + vbCritical, "An Error has Occured!"
        Resume Error_Handler_Exit
    End Function
    

ANSWER

    Dim currentReport As Report
    Dim strSQL As String

    ' Set the params
    Set currentReport = Screen.ActiveReport
    ' Replace double qoutes with single qoutes
    strSQL = Replace(currentReport.RecordSource, ";", "") & " AND " & currentReport.filter
    strSQL = Replace(strSQL, Chr(34), "'")
    strSQL = Replace(strSQL, ")", "")
    strSQL = Replace(strSQL, "(", "")
5
  • 1
    There is no question. What is the issue you have? Commented Sep 28, 2017 at 10:50
  • My Question is, how can i get the recordsource of the current active report, to convert to an HTML table. Commented Sep 28, 2017 at 15:46
  • This seems like you are asking for code. Where is the attempt at the HTML? Commented Sep 28, 2017 at 20:44
  • No, i'm asking for a way to extract the current active reports' query and filters applied by the user in SQL. Commented Sep 29, 2017 at 10:30
  • Not showing revised code to extract and build SQL string. Commented Oct 8, 2017 at 16:13

2 Answers 2

1

If i understand well your need,

After you have opened a report for preview, you would like to grab the filter you used to generate it and then mail it along with the report.

I would suggest to have a function that generate the report and then mail it

Function GenerateAndMailReport
    Dim strRecordSourceSample
    strRecordSourceSample = "reportQuery"
    Dim strFilterSample
    strFilterSample = "[SomeID] = 109902"
    Call DoCmd.OpenReport("reportName", acViewPreview, , strFilterSample)
    Call emailSupplier(strRecordSourceSample, strFilterSample) 'Passing the filter and record source to your mailing function
End Function

-EDIT-

If you already have access to your report object, then you can grab

currentReport.RecordSource
currentReport.Filter

https://msdn.microsoft.com/VBA/Access-VBA/articles/report-recordsource-property-access https://msdn.microsoft.com/VBA/Access-VBA/articles/report-filter-property-access

They will both return you strings which you can use to open a recordset

Dim SQL As String
Dim QRY As New ADODB.Recordset

SQL = currentReport.RecordSource & " WHERE " & currentReport.Filter
QRY.Open SQL, CurrentProject.Connection, adOpenDynamic, adLockOptimistic
While Not oQRY.EOF
HtmlLogicHere()
Wend
oQRY.Close

Just be carefull if you already have a WHERE clause in your recordset, the concatenating will be different.

Sign up to request clarification or add additional context in comments.

2 Comments

I want to extract the actual query from the currently active report with all the currently applied filters by the user.
This solved the issue, i extracted the replaced using the recordsource and filters. Thanks.
0

If the report Filter property is set in the OpenReport method or right click shortcut menu:

strSQL = Replace(Reports!report.RecordSource, ";","") & " WHERE " & Reports!report.Filter

Unfortunately, if report RecordSource is a dynamic parameterized query the parameter values will not be in the RecordSource sql, only the variable reference.

6 Comments

I have an open report, with filters applied by the user, and i want to extract it's SQL so i can use it in other locations
Exactly how is user applying filters? Both answers show how to extract the SQL statement.
He is applying them by right clicking in the report by mouse.
I just did a test. That method does set the report's Filter property so the suggested code should extract. Have you tried it?
This method works perfectly in getting the correct SQL. Yet i have a probmel with the code itself. I get the error "Item is not found in the collection.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.