VBA code to create a report in MS Access - ms-access

Can anyone help me create a code satatement that will allow me to create a report with the sQ statement below? The problem I'm having is that my form allows you to input a Cost center, but when I click on the command button to execute the code it asks me to input the cost center again before it shows me the report. I want to eliminate having to enter the cost center again and just take it from when it is enters on the form.
Private Sub CmdCC_Click()
Set mydb = CurrentDb
myCC = txtCC.Value
If IsNull(myCC) Or myCC = "" Then
MsgBox "Please enter a Cost Center!", vbCritical + vbOKOnly, pTitle
End If
sQ = "SELECT ZBASED.ACCT_UNIT, CenterName, ZBASED.ACCOUNT, ZBASED.ACCOUNT_DESC " & _
"FROM ZBASED, CCtable " & _
"WHERE (ZBASED.ACCT_UNIT = " & myCC & ") And (CenterNo = " & myCC & ") " & _
"ORDER BY ZBASED.ACCOUNT;"

If the report is already based on say,
SELECT ZBASED.ACCT_UNIT, CenterName,
ZBASED.ACCOUNT, ZBASED.ACCOUNT_DESC
FROM ZBASED, CCtable
(There is no point in using ORDER BY with a report, you must use the report's own Oder & Grouping properties)
You can use the Where argument of OpenReport:
DoCmd.OpenReport "ReportName", acViewPreview, , "ZBASED.ACCT_UNIT = " & myCC _
& " And CenterNo = " & myCC

All you have to do is reference the form you are calling the report from in the SQL, for example
SELECT foo FROM bar WHERE foo=[Forms]![frmReporting]![txtFoo]
You then have a button on frmFoo that opens the report, you can include some logic in before the docmd.OpenReport call to validate the input i.e. make sure they have entered a cost centre

Related

Problem to show graph in preview mode on in report

I have a form with a graphic and after modifying a certain field in the form, I change the number of graphic's records in this way:
Private Sub text_Cantidad_BeforeUpdate(Cancel As Integer)
Dim strsql As String
sql = "SELECT TOP " & CStr(text_Cantidad) & "Format([hora1],""hh:nn:ss"") AS Hora, TEMP_SET_POINT, TEMP_PAST_2 " & _
" , TEMP_PASTEURIZAD " & _
" FROM Qry_Registro WHERE Carpeta = '" & onodo.Parent.Text & "' AND Archivo = '" & Trim(onodo.Text) & _
"' ORDER BY Format([hora1],""hh:nn:ss""), Right(Format([hora1],""hh:nn:ss""),2);"
With Me.Gráfico1
.RowSourceType = "Table/Query"
.RowSource = sql
.Visible = True
.Object.Application.PlotBy = 2
End With
End Sub
Then with a button I want to print a report that has the same graph with the same properties and the same records. If I open the report in "report mode" everything is fine, but if I do it in "preview mode" I cannot change the recordsource property in any of the report or section's events.
The code I have for the button so far is:
Private Sub btn_Print_Click()
Dim strsql As String
TempVars.Add "SqlReport", ""
TempVars!SqlInformed = Me.Gráfico1.RowSource
'Error
DoCmd.OpenReport "Report", acViewPreview
'Ok
DoCmd.OpenReport "Informe1",acViewNormal
End Sub
The recordsource of a report can't be changed after the report is opened.
You shouldn't use dynamic sql to change the query of a form or report. If possible, use a WhereCondition parameter in the DoCmd.OpenForm or DoCmd.OpenReport statement. If your query Qry_Registro contains something like a unique ID, you can remove the dynamic "TOP" part from the report's query and replace it by a criterion for a WHERE clause using a subquery:
... WHERE ID IN (SELECT TOP x ID FROM ...
Placing all criteria in a variable, you can use that in the DoCmd.OpenReport statement.
strWhereClause = "ID IN (SELECT TOP " & CStr(text_Cantidad) & " ID FROM Qry_Registro " & _
"WHERE Carpeta = '" & onodo.Parent.Text & "' AND Archivo = '" & Trim(onodo.Text) & "' " & _
" ORDER BY Format([hora1], ""Long Time""))"
DoCmd.OpenReport ReportName:="MyReport", View:=acViewPreview, WhereCondition:=strWhereClause
Thanks a lot Wolfgang, but the issue is change the recordsource of chart in report. I solved placing in the properties of chart a query, then before open de report changed the propertie sql of querydef with the same sql that chart in form. Something like this
set querydef = currentdb.Querydefs("query_report_chart")
querydef.sql = "SELECT TOP " & CStr(text_Cantidad) & ....
DoCmd.OpenReport
Regards

Convert Access SQL To VBA

I am in need of converting this Access SQL Query to a VBA Query ->
SELECT informationTable.userID,
ConcatRelated('itemSold','[informationTable]',"userID='" & [userID] & "'") AS NameOfItemSold
FROM informationTable
GROUP BY informationTable.userID;
I tried ths VBA
DoCmd.RunSQL ("SELECT informationTable.userID,
ConcatRelated('itemsold','[informationTable]','userID= ' & Chr(34) & [userID] & Chr(34) & ') AS NameOfItemSold
Into CRInformationTable
FROM informationTable
GROUP BY informationTable.userID;")
but I get an error of
A RunSQL action requires an argument consisiting of an SQL statement
I did some testing. Assuming userID is number type field, see if this works for you:
DoCmd.RunSQL ("SELECT DISTINCT informationTable.userID, " & _
"ConcatRelated('itemsold','[informationTable]','userID=' & [userID]) AS NameOfItemSold " & _
"INTO CRInformationTable FROM informationTable;")
If userID is text type:
"ConcatRelated('itemsold','[informationTable]','userID=" & Chr(34) & "' & [userID] & '" & Chr(34) & "') AS NameOfItemSold " & _
Instead of Chr(34):
"ConcatRelated('itemsold','[informationTable]','userID=""' & [userID] & '""') AS NameOfItemSold " & _
I've used this nifty tool many times with great success.
Creating the form
The form just needs two text boxes, and a command button. SQL statements can be quite long, so you put the text boxes on different pages of a tab control.
Create a new form (in design view.)
Add a tab control.
In the first page of the tab control, add a unbound text box.
Set its Name property to txtSql.
Increase its Height and Width so you can see many long lines at once.
In the second page of the tab control, add another unbound text box.
Name it txtVBA, and increase its height and width.
Above the tab control, add a command button.
Name it cmdSql2Vba.
Set its On Click property to [Event Procedure].
Click the Build button (...) beside this property.
When Access opens the code window, set up the code like this:
Private Sub cmdSql2Vba_Click()
Dim strSql As String
'Purpose: Convert a SQL statement into a string to paste into VBA code.
Const strcLineEnd = " "" & vbCrLf & _" & vbCrLf & """"
If IsNull(Me.txtSQL) Then
Beep
Else
strSql = Me.txtSQL
strSql = Replace(strSql, """", """""") 'Double up any quotes.
strSql = Replace(strSql, vbCrLf, strcLineEnd)
strSql = "strSql = """ & strSql & """"
Me.txtVBA = strSql
Me.txtVBA.SetFocus
RunCommand acCmdCopy
End If
End Sub
Using the form
Open your query in SQL View, and copy the SQL statement to clipboard (Ctrl+C.)
Paste into the first text box (Ctrl+V.)
Click the button.
Paste into a new line in your VBA procedure (Ctrl+V.)
http://allenbrowne.com/ser-71.html

Open a form based on data from a recordset

I have an app that searches through customer information on a SQL Server database.
There are three forms:
The first allows the user to lookup info based on several different criteria, like Account no, Last name Phone Number, etc.
The second form correctly displays the information from the first form.
I want to open a third form based on a value in the result set on the second form, a field called Master_ID.
I have created a Global variable that stores the contents of the Master_ID field on the second form when the Master_ID field is clicked.
Then I want to execute the on click event on a button that contains the following code:
Private Sub tranHisBtn_Click()
Dim transferSQL As String
transferSQL = "SELECT dbo_Master_Accounts.Master_ID, dbo_Master_Accounts.FirstName, dbo_Master_Accounts.LastName, dbo_Transaction_Table.Date_of_Transaction, Format([dbo_Transaction_Table]![Time_of_Transaction],""hh:nn:ss ampm"") AS TranTime, dbo_Transaction_Table.Sku, dbo_Transaction_Table.Description, Right([dbo_Transaction_Table]![Description],6) AS tranAccnt, [dbo_Transaction_Table]![ArAmt]*-1 AS Amnt, dbo_Master_Accounts.Master_ID " & vbCrLf
transferSQL = transferSQL + "FROM dbo_Master_Accounts INNER JOIN dbo_Transaction_Table ON dbo_Master_Accounts.Master_ID = dbo_Transaction_Table.Account_Number " & vbCrLf
transferSQL = transferSQL + "WHERE (((dbo_Transaction_Table.Description) Like ""%Transfer To%"") AND ((dbo_Master_Accounts.Master_ID)=" & Chr$(34) & GBL_Master_Id & Chr$(34) & ")) " & vbCrLf
transferSQL = transferSQL + "ORDER BY dbo_Transaction_Table.Date_of_Transaction, Format([dbo_Transaction_Table]![Time_of_Transaction],""hh:nn:ss ampm"");"
Dim trancon As ADODB.Connection
Set trancon = CurrentProject.Connection
Dim tranRs As New ADODB.Recordset
tranRs.ActiveConnection = trancon
tranRs.CursorType = adOpenStatic
tranRs.Open transferSQL
'DoCmd.OpenForm "TransferbyNumFM" ', , , "Master_Id = 'transRs.fields(0)'"
MsgBox "good"
End Sub
I can't figure out how to set the record source for the third form. Everything runs perfectly until I try to open the third form.
As I said: Open the form with DoCmd and set the recordsource of the Form object in the OnOpen Event of the 3rd form to the SQL string you have. No need to create a recordset, either. And never try to pass a recordsource as a filter in a DoCmd.OpenForm
Oh, and my error: since you have a global variable (i.e. a public variable declared in a module) you don't even need to pass it as an OpenArgs, you can simply do the following on Button Click
DoCmd.OpenForm "TransferbyNumFm"
and then, in the class module of Form3 do
Option Compare Database
Option Explicit
Private Sub Form_Open(Cancel As Integer)
Dim transferSQL As String
transferSQL = _
"SELECT dbo_Master_Accounts.Master_ID, " & _
"dbo_Master_Accounts.FirstName, " & _
"dbo_Master_Accounts.LastName, " & _
"dbo_Transaction_Table.Date_of_Transaction, " & _
"Format([dbo_Transaction_Table]![Time_of_Transaction],'hh:nn:ss ampm') AS TranTime, " & _
"dbo_Transaction_Table.Sku, dbo_Transaction_Table.Description, " & _
"Right([dbo_Transaction_Table]![Description],6) AS tranAccnt, " & _
"[dbo_Transaction_Table]![ArAmt]*-1 AS Amnt " & _
"FROM dbo_Master_Accounts " & _
"INNER JOIN dbo_Transaction_Table ON dbo_Master_Accounts.Master_ID = dbo_Transaction_Table.Account_Number " & _
"WHERE(((dbo_Transaction_Table.Sku) Like '%Transfer%')) " & _
"ORDER BY dbo_Transaction_Table.Date_of_Transaction"
Me.RecordSource = transferSQL
End Sub
The Recordsource of Form3 can be unassigned before this point, though you will need it to add fields (but you can remove it later on)

ms access dynamically change label on report

I am printing a production ticket as a report using the following code:
Dim strCriteria As String
strCriteria = "SELECT [PkgSize] & chr$(32) & [PkgUnit] AS Pkg, tblProducts.ProductID, tblProducts.ProductPrintName, tblProducts.Grade, " _
& " tblCustomers.CompanyName, tblOrderDetails.ODEPriority, chr$(33) & chr$(70) & [tblProducts].[ProductID] & [tblCustomers].[ID] & chr$(33)as Expr1" _
& " FROM tblCustomers INNER JOIN (tblOrders INNER JOIN (tblProducts INNER JOIN tblOrderDetails ON " _
& " tblProducts.ProductID = tblOrderDetails.ODEProductFK) ON tblOrders.ORDOrderID = tblOrderDetails.ODEOrderID) ON " _
& " tblCustomers.ID = tblOrders.ORDCustomerID " _
& " WHERE (((tblProducts.ProductID)=[Forms]![frmInventoryTransfersManual]![cboTransferProductID]) " _
& " AND ((tblOrderDetails.ODEPriority)= " & varPriority & ") AND (([tblOrderDetails]![ODEQtyOrdered]-[tblOrderDetails]![ODEQtyProduced])>0))"
DoCmd.OpenReport "rptProductPaperLabelTCTRlogo", acViewPreview, , , , strCriteria
In the report I have:
Private Sub Report_Open(Cancel As Integer)
Me.RecordSource = Me.OpenArgs
End Sub
The various text boxes on the report use the following as their Control Sources: Grade, Expr1, ProductPrintName, Pkg, and CompanyName. (Expr1 produces a barcode for scanning the ticket.)
It works perfectly. However, I also need to print a label or, could be, a text box to form a border on the report. This label/textbox will be a color assigned to CompanyName. Therefore, the ticket can be seen quickly and know who the customer is just by knowing the color of this label/textbox.
Can anyone help me to change the color of a label/text box on the report dependent on the company name. We have about 20 different customers.
Add a color attribute to the table definition for the customer table. Add that color attribute to the recordsource of the form. Use that color to set the backcolor property of the control on the report in the appropriate eventhandler of the form, probably onChange?

Subform opening with previous filter

I've created a main form with a subform on it. The subform is filtered using a couple of combo boxes and command buttons on the main form.
For some strange reason when the form is closed and reopened, the subform is already showing as if it is filtered.
The method I'm using to filter the subform is to build an sql string that will be used as the subform's recordsource when a command button is pressed to apply the filter.
Here's the function that builds that sql string:
Public Function strSfaPaymentRecordSource() As String
strSfaPaymentRecordSource = "SELECT " _
& "[tblSfaRemittances].ID, [tblSfaRemittances].[SfaBudget], " _
& "[tblSfaRemittances].[PfrFundingLine], [tblSfaRemittances].[ContractNo], " _
& "[tblSfaRemittances].[LedgerDesc], [tblSfaRemittances].[TransDesc], " _
& "[tblSfaRemittances].[Period], [tblSfaRemittances].[Amount], [tblSfaRemittances].[Memo] " _
& "FROM tblSfaRemittances"
If Me.cboFundingLine > "" Or Me.cboReturnPeriod > "" Then
strSfaPaymentRecordSource = strSfaPaymentRecordSource & " WHERE"
End If
If Me.cboFundingLine > "" Then
strSfaPaymentRecordSource = strSfaPaymentRecordSource & " PfrFundingLine = '" & Me.cboFundingLine & "' And"
End If
If Me.cboReturnPeriod > "" Then
strSfaPaymentRecordSource = strSfaPaymentRecordSource & " Period = '" & Me.cboReturnPeriod & "'"
End If
If Right(strSfaPaymentRecordSource, 4) = " And" Then
strSfaPaymentRecordSource = Left(strSfaPaymentRecordSource, Len(strSfaPaymentRecordSource) - 4)
End If
End Function
And then the command button assigns the subform recordsource to the above string function:
Private Sub CmdApplyFilter_Click()
Me.frmSfaRemittances_sub.Form.RecordSource = strSfaPaymentRecordSource
End Sub
Now though, whenever I open the form, the subform is already filtered the same way (even if I filter it another way, close the form and come back to it).
I've checked the subform's recordsource and there is no WHERE clause saved there. I've also ran Debug.Print on the subform recordsource when the form and subform opens and still there is no WHERE clause being applied.
There's no code running on the any of the form or subform.form events, so I'm kind of at a loss as to why it's behaving this way. Any pointers would be appreciated :)