I have an Access database that opens multiple instances of 2 reports. The quantity depends on how many student registrations is captured per training run. This may be up to 25, meaning that when the user click on the "Print Documents" button, 25 instances of the 2 reports are opened. The first report is a student registration form, and the second is a indemnity form. Both these forms has certain data on them, like the personal details.
Opening the multiple reports is no issue. The first report is opened with the below code:
Z = 1
While Not Rst3.EOF
Set rpt(Z) = New Report_Rpt_StudentReg
rpt(Z).Visible = True
rpt(Z).Caption = "Student Registation " & Rst3.StudentID
'Append it to the collection.
clnClient.Add Item:=rpt(Z), Key:=CStr(rpt(Z).hwnd)
Rst3.MoveNext
Z = Z + 1
Wend
In the report Rpt_StudentReg On Load, there are code running to with SQL statements to retrieve all the data and fill the fields on the report. The second report (Waiver) is opened from within the first report with similar code below:
Set rptWaiver(Z) = New Report_Rpt_Indemnity
rptWaiver(Z).Visible = True
rptWaiver(Z).Caption = "Indemnity " & Rst3.StudentID
'Append it to our collection.
clnClient.Add Item:=rptWaiver(Z), Key:=CStr(rptWaiver(Z).hwnd)
My issue is none of the data is dispalyed on any of the reports.
If I run a single instance, everything is fine and the relevant data is displayed.
Your assistance is appreciated.
Thanks
Deon
I am opening multiple instances with no issues. In the report's On Load Event, there is code running each time the report is opened. I use SQL to retrieve the data from the tables. Debugging the code, retrieves the correct data, but the data is not on the report when it is opened. The On Load event code as follows:
Private Sub Report_Load()
Set Dbs = CurrentDb: Set Dbs1 = CurrentDb
Select Case Mode
Case "WithData"
If MyMode = "Certification" Then
SQL1 = "SELECT StudentID FROM Tbl_Certification WHERE CertNumber = " & Rst3!CertNumber & ";"
Set Rst1 = Dbs1.OpenRecordset(SQL1)
SQL = "SELECT * FROM Tbl_StudentReg WHERE IDNumber = " & Rst1!StudentID & ";"
Set Rst = Dbs.OpenRecordset(SQL)
Rst1.Close
Else
SQL = "SELECT * FROM Tbl_StudentReg WHERE IDNumber = " & Forms!Frm_StudentReg_Edit.IDNumber & ";"
Set Rst = Dbs.OpenRecordset(SQL)
End If
Set Rst = Dbs.OpenRecordset(SQL)
Me.FirstName = Rst!FirstName
Surname = Rst!Surname
PrevSurname = Rst!PrevSurname
IDNumber = Rst!IDNumber
BirthDate = Rst!BirthDate
AltIDNumber = Rst!AltIDNumber
AltIDType1 = Rst!AltIDType
'-------------------
SQL1 = "SELECT * FROM Tbl_AltID WHERE AltID = " & Rst!AltIDType & ";"
Set Rst1 = Dbs1.OpenRecordset(SQL1)
AltIDTypeDescr1 = Rst1!AltIDDescr
'-----------------------------
Nationality1 = Rst!Nationality
SQL1 = "SELECT * FROM Tbl_Nationality WHERE NationalityNo = " & Rst!Nationality & ";"
Set Rst1 = Dbs1.OpenRecordset(SQL1)
NationalityDescr1 = Rst1!NationalityDescr
'-------------------------------
When the reports are opened for preview, there is no data in the reports. They are all blank.
Related
So this is a problem which started happening a day ago.
I have an Access database file which stores a form for creating jobs, updating job sector, and deleting it from the MySQL table.
There are two tables that are used for this form: a local one stored in Access called "Job Route" and another through MYSQL ODBC Driver, ANSI 5.3 version called "To Do". The local table stores user-submitted data containing information on all job areas and state, while the MYSQL table only shows one job area at a time.
When a new entry is created, the text box details from the Access form are being stored onto both tables. Where each job contains up to 4 different sectors (e.g. [start date], [area1], [person in charge 1], [description1], ... [area4], [person in charge 4], [description4]). Whenever the data is being updated to its next state, in the local table only the job counter field is incremented, while every field in the MYSQL table called "To Do" is updated to its next state fields.
Connection to the server is good, and everything was running fine until an issue popped up in the updating function.
Basically how that function works is that on a listbox control, all current job data is being queried from the "To Do" table. The user selects an entry, and hits a button which loads the next sector information data from "Job Route", onto various textbox controls. The user can change those textbox inputs if they want - the only thing that is changed when the function runs is the "To Do". The information in "Job Route" remains the same. When the user hits the update button, the next sector field data is updated to "To Do", while only a counter in "Job Route" is being incremented to signify the current sector.
My problem is this. For the most part almost everything is running fine, but for one of the fields in "To Do" table does not update with the values it should from the textbox. So for instance if the textbox control was set to "Wyntile", the field name should be set to that, but for some reason a different value shows up instead, example="Apples". Here is the code:
Private Sub moveJob2_Click()
'get the job number
JobNum = Text31
CurrArea = DLookup("[Area]", "[To_Do]", "[Job_Number] =""" & JobNum & """")
area1 = DLookup("[Area1]", "[Job Route]", "[Job Number] =""" & JobNum & """")
area2 = DLookup("[Area2]", "[Job Route]", "[Job Number] =""" & JobNum & """")
area3 = DLookup("[Area3]", "[Job Route]", "[Job Number] =""" & JobNum & """")
area4 = DLookup("[Area4]", "[Job Route]", "[Job Number] =""" & JobNum & """")
'get what the current area is
Current = DLookup("[Current]", "[Job Route]", "[Job Number] =""" & JobNum & """")
'if the current area is the first area then check to make sure there is a second
'if so, then set the new area to it
If Current = 1 Then
If area2 = "---" Then
MsgBox area1 + " was the last area in the route. The job cannot be moved."
Exit Sub
End If
newArea = area2
ElseIf Current = 2 Then
If area3 = "---" Then
MsgBox area2 + " was the last area in the route. The job cannot be moved."
Exit Sub
End If
newArea = area3
ElseIf Current = 3 Then
If area4 = "---" Then
MsgBox area3 + " was the last area in the route. The job cannot be moved."
Exit Sub
End If
newArea = area4
Else
MsgBox area4 + " was the last area in the route. The job cannot be moved."
Exit Sub
End If
'set up link to both the To_Do and Job Route tables
Dim dbJobNumbers As DAO.Database
Dim rstJob As DAO.Recordset
Dim jobRoute As DAO.Recordset
Set dbJobNumbers = CurrentDb
Set rstJob = dbJobNumbers.OpenRecordset("To_Do")
Set jobRoute = dbJobNumbers.OpenRecordset("Job Route")
' >> Edit the job in the To_Do table
****' ERROR: Out of all these, only [Person_In_Charge] is being set to something
****' completely different from Text33, which wasn't changed by the user.
rstJob.FindFirst "[Job_Number]=""" + Text31 + """"
rstJob.Edit
rstJob("[Area]").Value = newArea
rstJob("[Person_In_Charge]").Value = Text33
rstJob("[Equipment]").Value = Text37
rstJob("[Description]").Value = Text35
rstJob.Update
'update the current area for the Job Route
jobRoute.FindFirst "[Job Number]=""" + Text31 + """"
jobRoute.Edit
jobRoute("[Current]").Value = CInt(Current) + 1
jobRoute.Update
'success message
MsgBox Text31 + " has been moved from " + CurrArea + " to " + newArea + "."
'requery the listboxes
Dim selectParas As String
selectParas = "SELECT [a].[Job_Number] as [Job Number], [a].[Description], [a].[Person_In_Charge] as [Person in Charge], [a].[Area] " & _
" FROM [To_Do] As [a];"
listRemoveJobs.RowSource = selectParas
listRemoveJobs.Requery
listChangeJobArea.RowSource = selectParas
listChangeJobArea.Requery
End Sub
The function has been running fine, and even now when I test it again it runs as programmed. Though today I recieved the "ODBC Insert on 'To Do' has failed" error, but that's for a different function. So I was thinking that something is wrong in the ODBC connection/MySQL table, but when I checked the table in phpmyadmin for the most part that table follows a similar format of other mysql tables used in Access.
Also to note, the person who had told me this issue runs on an old Windows XP version, where once before on that computer there were known issues of the defined OBDC ANSI 5.3 Driver instance completely disappearing from Access' Data Source list before. (The driver is still installed on Windows). That time, apparently the driver instance later re-appeared again magically in the D.S. list when that computer was restarted. ... I know this is rather long, but I can't seem to find the cause of why this updating error in Access is happening. Is there a known issue of ODBC having stability issues in connection? Why is the value changed to something completely different on update? Any insight would be appreciated.
While there is no reproducible example to help with your specific situation, consider running pure SQL UPDATE queries with binded parameters. Your area conditional logic can be rewritten into nested IIF expression. Possibly, this will simplify your problem and streamline your needs without DLookup or multiple recordset updates. Also, your re-assignment to RowSource is not necessary. Below utilizes parameterization, a best practice when running SQL in application layer:
SQL (save both below as Access queries)
mySavedJoinUpdateQuery
PARAMETERS Text33Param Text(255), Text35Param Text(255)
Text37Param Text(255), JobNumberParam Text(255);
UPDATE [To_Do] d
INNER JOIN [Job Route] r
ON d.Job_Number = r.Job_Number
SET [Area] = IIF([Current] = 1 AND [Area2] != '---', [Area2],
IIF([Current] = 2 AND [Area3] != '---', [Area3],
IIF([Current] = 3 AND [Area4] != '---', [Area4], [Area1)
)
),
[Person_In_Charge] = Text33Param,
[Equipment] = Text37Param,
[Description] = Text35Param
WHERE r.[Job Number] = JobNumberParam;
mySavedSimpleUpdateQuery
PARAMETERS JobNumberParam Text(255);
UPDATE [Job Route] r
SET r.[Current] = r.[Current] + 1
WHERE r.[Job Number] = JobNumberParam;
VBA
Private Sub moveJob2_Click()
Dim qdef As QueryDef
Dim selectParas As String
' UPDATE JOIN QUERY
Set qdef = CurrentDb.QueryDefs("mySavedJoinUpdateQuery")
qdef!JobNumberParam = Text31
qdef!Text33Param = Text33
qdef!Text35Param = Text35
qdef!Text37Param = Text37
qdef.Execute dbFailOnError
Set qdef = Nothing
' UPDATE SIMPLE QUERY
Set qdef = CurrentDb.QueryDefs("mySavedSimpleUpdateQuery")
qdef!JobNumberParam = Text31
qdef.Execute dbFailOnError
Set qdef = Nothing
' REQUERY LIST BOXES
listRemoveJobs.Requery
listChangeJobArea.Requery
End Sub
The list of problems with my software never seem to end! And once again, it's down to issues with SQL.
Previously, I'd asked on stackoverflow how to perform an inner join query (basically) - see my page for info - and now I have a new issue. I'm trying to update my "Students" database, however every time I do it returns with the error below:
Dynamic SQL generation is not supported against multiple base tables.
I'm not sure what I'm doing wrong, or how I go about fixing it. In my eyes, all I'm doing is trying to update the students table. The "inner join" part was for obtaining classes (see my last post for further clarification: Syntax Error (Missing Operator) In Query Expression ")
I've got the code for the relevant areas below:
Me.Validate()
Me.myDA.Update(Me.myDataSet.Tables("students"))
Me.myDataSet.AcceptChanges()
MsgBox("Registration Complete.", MsgBoxStyle.Information, "ASTRAS")
regiattendancedatagripview.Visible = False
reg_complete.Visible = False
reg_merit.Visible = False
reg_referral.Visible = False
reg_viewdetails.Visible = False
The above code is meant to update the students database that is being presented to me in a Datagridview. That datagridview has had information passed onto it from the "Classes" database, allowing it to display only the names required in the register. Code below:
If attendance_reg_periodComboBox.Text = "" Then
Else
Try
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\DATA.accdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT *
FROM [classes] INNER JOIN [students] ON
classes.StudentForename = students.Forename AND
classes.StudentSurname = students.Surname
WHERE classes.TeacherName ='" & personloggedon.Text & "'
AND classes.Day ='" & System.DateTime.Now.DayOfWeek.ToString & "'
AND classes.Period ='" & attendance_reg_periodComboBox.Text & "'",
con)
con.Open()
myDA = New OleDbDataAdapter(cmd)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(myDA)
myDataSet = New DataSet
myDA.Fill(myDataSet, "students")
regiattendancedatagripview.DataSource = myDataSet.Tables("students").DefaultView
con.Close()
con = Nothing
If regiattendancedatagripview.Rows.Count = 0 Then
Label7.Visible = True
regiattendancedatagripview.Visible = False
Else
regiattendancedatagripview.Visible = True
regiattendancedatagripview.Sort(regiattendancedatagripview.Columns(2), System.ComponentModel.ListSortDirection.Ascending)
reg_complete.Visible = True
reg_merit.Visible = True
reg_referral.Visible = True
reg_viewdetails.Visible = True
End If
Catch ex As Exception
MsgBox("An unknown error occured while trying to obtain the class register. Error details below:" & vbNewLine & vbNewLine & ex.Message, MsgBoxStyle.Critical, "ASTRAS")
End Try
End If
Essentially - my understanding is that the names from "classes" are being used to search and return a list of names from "students" and so display them in a datagridview. So how come my program can't update the absences column (LastKnownAbsence)?
I have a subform datasheet whose RecordSource can be variable. My database constructs an SQL query based on user selections (a different collection of columns with each query). The resulting query is intended to be the RecordSource for a datasheet on a subform. (Read-only view for user)
Problem:
The various queries produce the desired results when run on their own
Setting a resulting query as the datasheet's RecordSource does not produce any result (no columns/rows)
I suspect I need to insert the query's attributes into the subform in order to see any results (much like "Add Existing Fields" in the menu strip).
Question:
Any pointers to get me off square one?
Thank you!
Remove the datasheet form from your subform object and leave the source object property empty.
Create a new query (sql doesn't matter) and name it qryTemp (or whatever you like).
Then whenever you want to set the source for the subform, use this
CurrentDb.QueryDefs("qryTemp").SQL = "<your new sql here>"
<yoursubformobject>.SourceObject = "Query.qryTemp".
Here is an example I use to populate a sub-form:
Private Sub cmdFind_DisplayName_Click()
Dim dbs As Database, rstPatient As Recordset
Dim txtDisplayName, strQuote As String
strQuote = Chr$(34)
On Error GoTo ErrorHandler
Me.OrderBy = "DISPLAYNAME"
Me.OrderByOn = True
Set dbs = CurrentDb
Set rstPatient = Me.RecordsetClone
txtDisplayName = Trim(InputBox("Please Enter Patient Name ", "Patient Find By Name"))
txtDisplayName = UCase(txtDisplayName) & "*"
If IsNull(txtDisplayName) Then
MsgBox ("No Patient Name Entered - Please Enter a Valid Patient Name")
Else
rstPatient.FindFirst "[DISPLAYNAME] Like " & strQuote & txtDisplayName & strQuote
If Not (rstPatient.NoMatch) Then
Me.Bookmark = rstPatient.Bookmark
Me.Refresh
Else
MsgBox ("Patient Not Found - Please Enter a New Patient Name")
End If
End If
GoTo Exit_cmdFind_Click
ErrorHandler:
MsgBox LTrim(RTrim(Me.NAME)) + "." + "Patient Find By Display Name - " + "Error: " + AccessError(Err.Number)
Exit_cmdFind_Click:
rstPatient.Close
Set dbs = Nothing
Set rstPatient = Nothing
End Sub
The below code works great for refreshing an external link in vba however is there a way of changing the location of the link?
I can do this using linked table manager when ticking the 'Always prompt for new location', but I would like to do this via VBA, so that I could create a button for users to press to locate the new workbook
Select new workbook, Relink external excel workbook.
Function Relink()
Set db = CurrentDb
Set tdf = db.TableDefs("Sales")
tdf.Connect = "Excel 5.0;HDR=YES;IMEX=2;" & _
"DATABASE=C:\Sales.xlsb"
tdf.RefreshLink
End Function
I use this function to re-link my tables from a table, based on whether I am working on my c:\ drive or the network. I think you could modify this to have the user enter a file location, or use a file dialog to browse to a location.
Function relink_tables()
If Left(CurrentDb().Name, 2) = "C:" Then
source = "local"
Else: source = "network"
End If
Set RS = CurrentDb.OpenRecordset("select * from [linked table source] where source='" & source & "'")
source = RS.Fields("path")
For Each R In References
If InStr(R.Name, "Common Tables") > 0 Then Application.References.Remove R
Next R
Application.References.AddFromFile source
x = 0
Set TDefs = CurrentDb().TableDefs
For Each table In TDefs
If InStr(table.Connect, "Common Tables") = 0 Then GoTo NT
table.Connect = ";DATABASE=" & source
table.RefreshLink
x = x + 1
NT:
Next table
Finish:
MsgBox "remapped " & x & " tables"
End Function`enter code here`
Here's a function I use to allow the user to browse to a file and select it. You can call this function to get a file name in the prior function instead of getting it from the table.
Public Function Get_File(Optional ftype = "xls")
Dim fd As Object
Const msoFileDialogFolderPicker = 4
Const msoFileDialogFilePicker = 3
Const msoFileDialogViewDetails = 2
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.ButtonName = "Select"
fd.InitialView = msoFileDialogViewDetails
fd.Title = "Select File"
fd.InitialFileName = "MyDocuments\"
fd.Filters.Clear
fd.Filters.Add "Files", "*." & ftype & "*"
'Show the dialog box and get the file name
If fd.Show = -1 Then
Get_File = fd.SelectedItems(1)
Else
Get_File = ""
End If
End Function
I am creating a form in my Access 2010 Database to input employee users. The code also is used to edit existing users.
To avoid confusion - the column names I will be talking about (which exist in the table 'Employees') are LastName and FirstName, while the input fields on my form are First and Last.
The form I am creating is for insertion OR updating of employee data. When the user types into the First field, Last is auto-populated with a list of values from the LastName column where FirstName = Me.First. If the administrator selects a last name that was populated in the box (rather then typing one in themselves), than the existing record is opened for editing.
My SQL for the Last combobox
SELECT DISTINCT Last
FROM [Employees]
WHERE First = Forms![Employees]!First;
My Code for after the Last combox is updated (Full = "LastName, FirstName")::
Private Sub Last_AfterUpdate()
Dim records As Recordset
Dim tmp As String
Dim db As Database
Set db = CurrentDb
If (DCount("Full", "Employees", "Full='" & Me.Last & "," & Me.First & "'") >= 1) Then
tmp = Me.Last & "," & Me.First
Set records = db.OpenRecordset("SELECT * from [Employees] WHERE Full = '" & tmp & "'")
Me.Recordset.FindFirst "ID1=" & records.Fields("ID1")
End If
If (DCount("Full", "Employees", "Full='" & Me.Last & ", " & Me.First & "'") >= 1) Then
tmp = Me.Last & ", " & Me.First
Set records = db.OpenRecordset("SELECT * from [Employees] WHERE Full = '" & tmp & "'")
Me.Recordset.FindFirst "ID1=" & records.Fields("ID1")
End If
End Sub
MY ISSUE:
If an existing record is found, than the record is opened correctly. Before the record is opened, however, a new one is saved with the data the administrator has input thus far. This is the issue, I don't want the data saved, but I don't know exactly why it is occurring in the first place. Is there a way to stop the old record from saving, aside from deleting it programmatically?