Problem to show graph in preview mode on in report - ms-access

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

Related

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

Apply filter on subform and open a report based on the filter

I have a subform which allows user to select a value for "ACFTsn" I would like to apply a filter to a table entitled "Logbook", where "sn"(field on the table) = ACFTsn
the following is attached to a button on the subform
Me.Form.Filter = "table![Logbook].SN=me.ACFTsn"
Me.FilterOn = True
DoCmd.openreport "logbook", acViewReport, Filter
When I step through the code, I receive error 3071/ expression typed incorrectly or too complex to be evaluated.
I am sure there are syntax errors, as this is my first attempt at a filter with VBA, and I'm not sure this is the correct way to apply it to the report.
Alternatively, you can use the ApplyFilter method or even SetFilter (for MS Access 2010+):
Dim strfilter As String
strfilter = "[SN] = '" & Me!ACFTsn.Value & "'"
DoCmd.ApplyFilter , strfilter ' FILTERS FORM
DoCmd.OpenReport "logbook", acViewReport, strfilter ' FILTERS REPORT
It should be this simple:
Me.Filter = "[SN] = '" & Me!ACFTsn.Value & "'"
Me.FilterOn = True
If SN is not a string:
Me.Filter = "[SN] = " & Me!ACFTsn.Value & ""
Me.FilterOn = True
To apply the same filter on the report:
DoCmd.openreport "logbook", acViewReport, , Me.Filter

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)

Issue with Data passing from one form to another form in MS Access VBA

Can anyone solve my issue
Form: SB_1 (this is a Customer Invoice creation form)
Form: Add_NewRelations (this is a Customer details adding form)
I have used a VBA code in Form: SB_1 on a cmd (Button) for Data passing from one form to another form of Add_NewRelations for New Customer details are needed to update.
So that VBA working is good as per Code Tag. But some of exist customer details are no need to update into Form: Add_NewRelations. So in this case i have added IF Statement with DCount in the VBA code.
When i added If statement with DCount then whole VBA is didn't working... i think DCount is wrong... how can i correction it??
Can anyone please replay how to solve this problem??
Private Sub Button_Click()
On Error GoTo ErrorHandler
'Me.Refresh
Dim strCriteria As String
strCriteria = "CIDCustomer = '" & Trim(Trim(Me!RID) & " " & Trim(Me!RName)) & "'"
'If DCount("*", "CIDCustomer", "RelationsQry") > 0 Then
'Cancel = True
'Else
If DCount("*", "RelationsQry", strCriteria) > 0 Then
Cancel = True
Else
'If Not IsNull([Customer]) Then
'Me.Visible = False
DoCmd.OpenForm "Add_NewRelations", acNormal, , , , acWindowNormal
Forms![Add_NewRelations].Form.RID = Me.CID2
Forms![Add_NewRelations].Form.RName = Me.Customer
Forms![Add_NewRelations].Form.RType.Value = "Customer"
Forms![Add_NewRelations].Form.Address = Me.Address
Forms![Add_NewRelations].Form.TINNumber = Me.TINNumber
Forms![Add_NewRelations].Form.TownVLG = Me.TownVLG
Forms![Add_NewRelations].Form.RName.SetFocus
'Forms![Add_NewRelations].Visible = False
'DoCmd.Close
End If
ErrorHandler:
End Sub
To pass the quotes into the SQL you need to escape them, and you need additional single quotes as well for the elements of the criteria.
Instead of:
strCriteria = "CIDCustomer = '" & Trim(Trim(Me!RID) & " " & Trim(Me!RName)) & "'"
try
strCriteria = "" "CIDCustomer = '" & Trim(Trim(Me!RID) & "' & " " & '" Trim(Me!RName)) & "'" ""

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