Dynamic report with crosstab query doesn't work (1 Viewer)

JessicaVdb

Registered User.
Local time
Today, 22:45
Joined
Jul 4, 2017
Messages
32
I am making a dynamic report with a crosstab query. My problem is that the report need to have changing headings. I looked on this site and many others, to find a solution. But I still havent found one. I put here my code in the hope someone knows what the problem is in my VBA-code.

Thanks

JessicaVdb

Code:
    '  Constant for maximum number of columns EmployeeSales query would
    Const conTotalColumns = 18
    '  Variables for Database object and Recordset.
    Dim dbsReport As DAO.Database
    Dim rstReport As DAO.Recordset
    '  Variables for number of columns and row.
    Dim intColumnCount As Integer
    Dim lngRgColumnTotal(1 To conTotalColumns) As Long
Private Function xtabCnulls(varX As Variant)
    ' Test if a value is null.
    If IsNull(varX) Then
        ' If varX is null, set varX to 0.
        xtabCnulls = 0
    Else
        ' Otherwise, return varX.
        xtabCnulls = varX
    End If
End Function
Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
    ' Put values in text boxes and hide unused text boxes.
    Dim intX As Integer
    '  Verify that you are not at end of recordset.
    If Not rstReport.EOF Then
        '  If FormatCount is 1, put values from recordset into text boxes in "Detail" section.
        If Me.FormatCount = 1 Then
            For intX = 1 To intColumnCount
                '  Convert Null values to 0.
                Me("Col" + Format(intX)) = xtabCnulls(rstReport(intX - 1))
            Next intX
            '  Hide unused text boxes in the "Detail" section.
            For intX = intColumnCount + 2 To conTotalColumns
                Me("Col" + Format(intX)).Visible = False
            Next intX
            '  Move to next record in recordset.
            rstReport.MoveNext
        End If
    End If
End Sub
Private Sub Detail_Print(Cancel As Integer, PrintCount As Integer)
    Dim intX As Integer
    Dim lngRowTotal As Long
    '  If PrintCount is 1, initialize rowTotal variable.
    '  Add to column totals.
    If Me.PrintCount = 1 Then
        lngRowTotal = 0
        
        For intX = 2 To intColumnCount
            '  Starting at column 2 (first text box with crosstab value),
            '  compute total for current row in the "Detail" section.
            lngRowTotal = lngRowTotal + Me("Col" + Format(intX))
            '  Add crosstab value to total for current column.
            lngRgColumnTotal(intX) = lngRgColumnTotal(intX) + Me("Col" + Format(intX))
        Next intX
        
        '  Put row total in text box in the "Detail" section.
        Me("Col" + Format(intColumnCount + 1)) = lngRowTotal
        '  Add row total for current row to grand total.
        lngReportTotal = lngReportTotal + lngRowTotal
    End If
End Sub
Private Sub Detail_Retreat()
    ' Always back up to previous record when "Detail" section retreats.
    rstReport.MovePrevious
End Sub
Private Sub PageHeaderSection_Format(Cancel As Integer, FormatCount As Integer)
    Dim intX As Integer
    
    '  Put column headings into text boxes in page header.
    For intX = 1 To intColumnCount
        Me("Head" + Format(intX)) = rstReport(intX - 1).Name
    Next intX
    '  Make next available text box Totals heading.
    Me("Head" + Format(intColumnCount + 1)) = "Totals"
    '  Hide unused text boxes in page header.
    For intX = (intColumnCount + 2) To conTotalColumns
        Me("Head" + Format(intX)).Visible = False
    Next intX
End Sub
Private Sub Report_Close()
    On Error Resume Next
    '  Close recordset.
    rstReport.Close
End Sub
Private Sub Report_NoData(Cancel As Integer)
    MsgBox "Probeer opnieuw", vbExclamation, "No Records Found"
    rstReport.Close
    Cancel = True
End Sub
Private Sub Report_Open(Cancel As Integer)
    '  Create underlying recordset for report using criteria entered.
    Dim intX As Integer
    Dim qdf As QueryDef
    Dim frm As Form
    '  Set database variable to current database.
    Set dbsReport = CurrentDb
    Set frm = Forms!MainMenuF
    '  Open QueryDef object.
    Set qdf = dbsReport.QueryDefs("TrainingMatrixQ_Kruistabel")
    '  Open Recordset object.
    Set rstReport = qdf.OpenRecordset()
   
    '  Set a variable to hold number of columns in crosstab query.
    intColumnCount = rstReport.Fields.Count
End Sub
Private Sub ReportHeader_Format(Cancel As Integer, FormatCount As Integer)
    '  Move to first record in recordset at the beginning of the report
    '  or when the report is restarted. (A report is restarted when
    '  you print a report from Print Preview window, or when you return
    '  to a previous page while previewing.)
    rstReport.MoveFirst
    'Initialize variables.
    InitVars
End Sub
 

isladogs

MVP / VIP
Local time
Today, 21:45
Joined
Jan 14, 2017
Messages
18,247
Not the same but parts of it are similar.
Let me know how you get on with mine
 

isladogs

MVP / VIP
Local time
Today, 21:45
Joined
Jan 14, 2017
Messages
18,247
It really doesn't wont to work for me. Everytime I add someting, someting else doesn't work again. Could you help me?

https://ufile.io/ogfs0

Thank

JessicaVdb


Three bits of advice
1. Use the same SQL for the report record source & for the TRANSFORM statement in Report_Open event

2. You need to tell the code which column is the first for your crosstab columns.
For example, the report in my example has 2 columns then the crosstab bit starts at column 3
Yours may be different so modify the code accordingly

3. Make sure you have enough columns for the data you are reporting on and do some error trapping code (as I did) just in case

If for example you have 40 columns (Col1 -> Col40) in your report and there are 41 items you will get an error saying it can't find Col41 ... unless you error trap for that possibility

4. If you don't need a totals row just comment out that bit of the code

If still having problems, please upload your db to this site.
I've no idea what the site is you listed but here's better for me

If so, please give me something more to work with ...
1. What are you adding? What stops working?
In other words what EXACTLY is the problem

2. With the data you are using, what should be the report headings be?
 

JessicaVdb

Registered User.
Local time
Today, 22:45
Joined
Jul 4, 2017
Messages
32
Three bits of advice
1. Use the same SQL for the report record source & for the TRANSFORM statement in Report_Open event


I don't know what you mean with this. The rest I am trying.

Thanks
 

JessicaVdb

Registered User.
Local time
Today, 22:45
Joined
Jul 4, 2017
Messages
32
Three bits of advice
1. Use the same SQL for the report record source & for the TRANSFORM statement in Report_Open event

2. You need to tell the code which column is the first for your crosstab columns.
For example, the report in my example has 2 columns then the crosstab bit starts at column 3
Yours may be different so modify the code accordingly

3. Make sure you have enough columns for the data you are reporting on and do some error trapping code (as I did) just in case

If for example you have 40 columns (Col1 -> Col40) in your report and there are 41 items you will get an error saying it can't find Col41 ... unless you error trap for that possibility

4. If you don't need a totals row just comment out that bit of the code

If still having problems, please upload your db to this site.
I've no idea what the site is you listed but here's better for me

If so, please give me something more to work with ...
1. What are you adding? What stops working?
In other words what EXACTLY is the problem

2. With the data you are using, what should be the report headings be?

I have been triyng what you said. I removed the total row code. Also have I the first and second row as you that need to be different. But I still get some issues -> Someting is wrong in the code I think.

The heading should be Name, as you can find in the query's. Obviously there are a lot more names, this is just for putting on this site.
 

Attachments

  • Database1.accdb
    988 KB · Views: 181

isladogs

MVP / VIP
Local time
Today, 21:45
Joined
Jan 14, 2017
Messages
18,247
Jessica

I've spent well over an hour on this and I'm sorry to say its a mess.

The problems are mostly not to do with the crosstab report itself.
Your own code / data is flawed - you shouldn't have posted something in this state expecting anyone to make sense of it

1. The database didn't compile as you had deleted part of my error handling in Report_Open event and also 'lost' the Dim line:
Code:
Dim strSQL As String, strProc As String

2. Next I looked at your form which had 2 combo boxes with no labels and nothing to guide me.
I added labels & a button to run the report.
N.B I removed your after update macro as it was distracting me with the task in hand

2. I then ran the report but your TRANSFORM statement threw up multiple errors:

strSQL = "PARAMETERS [forms]![Menu]![Shift] Text ( 255 ), [forms]![Menu]![Type] Text ( 255 )" & _
"TRANSFORM Max(TrainingQ.[Level of training]) AS [MaxVanLevel of training]" & _
"SELECT TrainingQ.Shift, TrainingQ.Subject, TrainingQ.TankType" & _
"FROM TrainingQ" & _
"WHERE (((TrainingQ.Shift) = [Forms]![Menu]![Shift]) And ((TrainingQ.TankType) = [Forms]![Menu]![Type]))" & _
"GROUP BY TrainingQ.Shift, TrainingQ.Subject, TrainingQ.TankType" & _
"PIVOT TrainingQ.Name;"

Mistakes include:
a) PARAMETERS line shouldn't be there - the WHERE line does the filtering
b) there should be a space at the start of each line
c) The WHERE line needs delimiters '" ... "' (see below)
d) The Shift field is actually the 2nd column of your shift combo box i.e. Column(1) as counting starts at zero.
However this won't work in a SQL statement so I added hidden textboxes txtShift, txtType on your form to 'pull' the required values from the combo boxes
e) Name is a reserved word in Access - change to FullName
f) your report has a field called Station NOT Subject
g) you can't get MAX value for Level of Training when the field has both numbers and values = OK

ALWAYS CHECK your SQL statement is valid and will give results BEFORE you use it in a report

By now I'm more than fed up....and I'm sorry but I've given up

Perhaps if you sort out all the issues I've described above and get it into a workable state, I'll reconsider
BUT for now I'm outta here!
 

JessicaVdb

Registered User.
Local time
Today, 22:45
Joined
Jul 4, 2017
Messages
32
Jessica

I've spent well over an hour on this and I'm sorry to say its a mess.

The problems are mostly not to do with the crosstab report itself.
Your own code / data is flawed - you shouldn't have posted something in this state expecting anyone to make sense of it

1. The database didn't compile as you had deleted part of my error handling in Report_Open event and also 'lost' the Dim line:
Code:
Dim strSQL As String, strProc As String
2. Next I looked at your form which had 2 combo boxes with no labels and nothing to guide me.
I added labels & a button to run the report.
N.B I removed your after update macro as it was distracting me with the task in hand

2. I then ran the report but your TRANSFORM statement threw up multiple errors:



Mistakes include:
a) PARAMETERS line shouldn't be there - the WHERE line does the filtering
b) there should be a space at the start of each line
c) The WHERE line needs delimiters '" ... "' (see below)
d) The Shift field is actually the 2nd column of your shift combo box i.e. Column(1) as counting starts at zero.
However this won't work in a SQL statement so I added hidden textboxes txtShift, txtType on your form to 'pull' the required values from the combo boxes
e) Name is a reserved word in Access - change to FullName
f) your report has a field called Station NOT Subject
g) you can't get MAX value for Level of Training when the field has both numbers and values = OK

ALWAYS CHECK your SQL statement is valid and will give results BEFORE you use it in a report

By now I'm more than fed up....and I'm sorry but I've given up

Perhaps if you sort out all the issues I've described above and get it into a workable state, I'll reconsider
BUT for now I'm outta here!

I'm sorry, it was late last night. My crosstab query works perfectly now. Only one problem, how do I set my combobox value to the textbox? I have set some code, but that doesn't work. The code (that is not working) that I use now:
Code:
Private Sub cmbShift_Change()
    txtShift = cmbShift
End Sub

OR

Code:
Private Sub cmbShift_Change()
    Me.txtShift.Text = Me.cmbShift.Value
End Sub
 

JessicaVdb

Registered User.
Local time
Today, 22:45
Joined
Jul 4, 2017
Messages
32
Also I can't exactly find in the code where I need to change the query that need to be used for my names to appear. This is what I get in my report write now:
 

Attachments

  • Knipsel.PNG
    Knipsel.PNG
    20.4 KB · Views: 205

isladogs

MVP / VIP
Local time
Today, 21:45
Joined
Jan 14, 2017
Messages
18,247
Use this

Code:
Private Sub cmbShift_AfterUpdate()
    Me.txtShift =Me.cmbShift.Column(1)
End Sub

Report query code is in 2 places:
a) The report record source - open in design view & look in properties window
b) Transform statement in the Report_Open event
When I gave up, I had this:

Code:
strSQL = "TRANSFORM Max(TrainingQ.[Level of training]) AS [MaxVanLevel of training]" & _
        " SELECT TrainingQ.Shift, TrainingQ.Station, TrainingQ.TankType" & _
        " FROM TrainingQ" & _
        " GROUP BY TrainingQ.Shift, TrainingQ.Station, TrainingQ.TankType" & _
        " PIVOT TrainingQ.FullName;"

Which gave me the report name headers but not the values:



I'll leave you to get the values in the report
I also got 2 parameter windows appearing for each name
Again I'll leave that for you to solve....
 

Attachments

  • JessicaReport.PNG
    JessicaReport.PNG
    18 KB · Views: 1,562

JessicaVdb

Registered User.
Local time
Today, 22:45
Joined
Jul 4, 2017
Messages
32
Use this

Code:
Private Sub cmbShift_AfterUpdate()
    Me.txtShift =Me.cmbShift.Column(1)
End Sub
Report query code is in 2 places:
a) The report record source - open in design view & look in properties window
b) Transform statement in the Report_Open event
When I gave up, I had this:

Code:
strSQL = "TRANSFORM Max(TrainingQ.[Level of training]) AS [MaxVanLevel of training]" & _
        " SELECT TrainingQ.Shift, TrainingQ.Station, TrainingQ.TankType" & _
        " FROM TrainingQ" & _
        " GROUP BY TrainingQ.Shift, TrainingQ.Station, TrainingQ.TankType" & _
        " PIVOT TrainingQ.FullName;"
Which gave me the report name headers but not the values:



I'll leave you to get the values in the report
I also got 2 parameter windows appearing for each name
Again I'll leave that for you to solve....

Thank you, I apprechiate it. The code you gave worked well. I'm gonne use my sql (sinds it works) but I'm gonne look at you're code.
 

JessicaVdb

Registered User.
Local time
Today, 22:45
Joined
Jul 4, 2017
Messages
32
If I put parameters in, this is the error I get.



This is the code I am using now:

Code:
"PARAMETERS [forms]![MainMenuF]![txtShift] Text (3 ), [forms]![MainMenuF]![txtType] Text ( 15);" & _
        "TRANSFORM Last(TrainingMatrixQ.LevelOfTraining) AS LastOfLevelOfTraining" & _
        "SELECT TrainingMatrixQ.Subject, TrainingMatrixQ.Station, TrainingMatrixQ.TankType" & _
        "FROM TrainingMatrixQ" & _
        "WHERE (((TrainingMatrixQ.Shift)=[forms]![MainMenuF]![txtShift]) AND ((TrainingMatrixQ.TankType)=[forms]![MainMenuF]![txtType]))" & _
        "GROUP BY TrainingMatrixQ.Shift, TrainingMatrixQ.Subject, TrainingMatrixQ.Station, TrainingMatrixQ.TankType" & _
        "PIVOT TrainingMatrixQ.FullName;"

I don't get names or values in my report.
 

Attachments

  • Knipsel.PNG
    Knipsel.PNG
    4 KB · Views: 616

Minty

AWF VIP
Local time
Today, 21:45
Joined
Jul 26, 2013
Messages
10,371
You seem to have lost all the trailing spaces in your sql string. If you debug.print it it comes out like this
Code:
PARAMETERS [forms]![MainMenuF]![txtShift] Text (3 ), [forms]![MainMenuF]![txtType] Text ( 15);TRANSFORM Last(TrainingMatrixQ.LevelOfTraining) AS LastOfLevelOfTrainingSELECT TrainingMatrixQ.Subject, TrainingMatrixQ.Station, TrainingMatrixQ.TankTypeFROM TrainingMatrixQWHERE (((TrainingMatrixQ.Shift)=[forms]![MainMenuF]![txtShift]) AND ((TrainingMatrixQ.TankType)=[forms]![MainMenuF]![txtType]))GROUP BY TrainingMatrixQ.Shift, TrainingMatrixQ.Subject, TrainingMatrixQ.Station, TrainingMatrixQ.TankTypePIVOT TrainingMatrixQ.FullName;
Note the lack of spaces between the clauses.
As Riddders mentioned - you should always check your sql works in a query window, unless you are really good at writing queries "off pat".
 

JessicaVdb

Registered User.
Local time
Today, 22:45
Joined
Jul 4, 2017
Messages
32
You seem to have lost all the trailing spaces in your sql string. If you debug.print it it comes out like this
Code:
PARAMETERS [forms]![MainMenuF]![txtShift] Text (3 ), [forms]![MainMenuF]![txtType] Text ( 15);TRANSFORM Last(TrainingMatrixQ.LevelOfTraining) AS LastOfLevelOfTrainingSELECT TrainingMatrixQ.Subject, TrainingMatrixQ.Station, TrainingMatrixQ.TankTypeFROM TrainingMatrixQWHERE (((TrainingMatrixQ.Shift)=[forms]![MainMenuF]![txtShift]) AND ((TrainingMatrixQ.TankType)=[forms]![MainMenuF]![txtType]))GROUP BY TrainingMatrixQ.Shift, TrainingMatrixQ.Subject, TrainingMatrixQ.Station, TrainingMatrixQ.TankTypePIVOT TrainingMatrixQ.FullName;
Note the lack of spaces between the clauses.
As Riddders mentioned - you should always check your sql works in a query window, unless you are really good at writing queries "off pat".

Okay, the query works and the report works. But still the names and values doesn't appear in the report.
 

isladogs

MVP / VIP
Local time
Today, 21:45
Joined
Jan 14, 2017
Messages
18,247
Thought I may as well upload where I've got to.
As I said previously, when I gave up last night I had the names on the report but not the values.

I've made one further change - remember I said to use the same SQL for the report record source - I've changed it to a crosstab query & I now get names & values AND no parameter messages. Hooray.

However its not filtered so you get blank rows.
When I filtered the source query, it failed again

Also to repeat what I said originally, you do NOT need to use the PARAMETERS line in strSQL statement.
I realise I'm saying the EXACT opposite of Minty here
In fact if you do include it, you'll get another error

My code includes various versions of strSQL statment - all had issues....

I've been using dynamic crosstab queries for many years - many far more complex than this one - and I've never had this issue before.

So you 'just' need to sort the filtering and you're done

Sorry I can't quite fix the problem - hopefully you will be able to do so
(or perhaps someone else may join in the fun and games....)

My gut feeling is that your source data is the problem
 

Attachments

  • Database1 - CR.accdb
    684 KB · Views: 150

Users who are viewing this thread

Top Bottom