ms access dynamically change label on report - ms-access

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?

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

Main form and subform for 1:m tables in Access 2013

I want to display the fields from two tables on a form. The two tables are ‘Customer’ and ‘Vehicle’. (1:m). The customer fields will be displayed in the main form and to display the Vehicle fields I have put a subform in Datasheet view and I added a textbox for vehicleID. When I enter CustomerID and click a commandbutton on another form this main form (frmCustomerDetails) will be opened with the subform (sfrmVehicle).
The customer fields are correctly displayed in the main form. There is no error messages, but I cant see the Vehicle fields in the subform. It just displays #Name? six times. There are six records in the vehicle table, so I think it doesn’t even filter the vehicleid for this customer. (Only two records in the vehicle table belong to this customer.)
My Ms Access 2013 VBA code is;
Dim strSQL1 As String
Dim rs1 As DAO.Recordset
strSQL1 = "SELECT Customer.CustomerID, " & _
" Customer.fName, " & _
" Customer.lName, " & _
" Customer.Telephone, " & _
" Customer.MobilePhone, " & _
" Customer.EMail, " & _
" Customer.Address1, " & _
" Customer.Address2, " & _
" Customer.City, " & _
" Customer.State, " & _
" Customer.PostalCode, " & _
" Vehicle.VehicleID " & _
"FROM Customer INNER JOIN Vehicle ON Customer.CustomerID = Vehicle.CustomerID;"
Set rs1 = CurrentDb.OpenRecordset(Name:=strSQL1, Type:=dbOpenDynaset)
rs1.FindFirst "[CustomerID] =""" & txtIDs & """"
DoCmd.OpenForm "frmCustomerDetails"
[Forms]![frmCustomerDetails]![txtCustomerName] = rs1.Fields!fName
..
..
[Forms]![frmCustomerDetails]![sfrmVehicle]![txtVehicleId].ControlSource = rs1.Fields!VehicleID
rs1.Close
Set rs1 = Nothing
Do I have to have two different SQL statements for main form and subform? Then how to do filtering. Need help. please.
To do the filtering on the subform all you need is this code;
Me.sfrmVehicle.Form.Filter = "[vehicleID]=" & Me.vehicleIDTextBox
Me.sfrmVehicle.Form.FilterOn = True
And for the name error in the subform, that could be because you haven't selected the correct source object in the data tab in its property sheet.
Edit: With the SQL statements, like Andre said, you don't need them.

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)

VBA code to create a report in 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