Access 2013: Getting error message "Method 'Open' of object' _Recordset' failed " when trying to populate text boxes with data in a form - sql

I'm having an issue with this piece of VBA code. I'm trying to populate text boxes on a form in Access 2013 with data from a table called Module. Once a user selects an available module from a combo box and clicks a button called 'btnSelectmodule', the relevant data should feed into the text boxes. Instead I'm getting an error; " Method 'Open' of object' _Recordset' failed "
Private Sub btnSelectmodule_Click()
Dim strmoduleid As String
Dim rstmodule As New ADODB.Recordset
strmoduleid = CVar(cmbSelectmodule)
rstmodule.Open "SELECT Module.ModuleID, Module.ModuleName,
Module.ModuleShortCode, Module.Level, Module.Semester, Module.CATPoints,
Module.FacultyCode, Module.Active, Module.Type FROM [Module]
WHERE (((CVar([ModuleID]))='" & CVar(strmoduleid) & "'));",
CurrentProject.Connection, adOpenKeyset, adLockOptimistic
If (rstmodule("ModuleID") <> "") Then
txtmoduleid.Value = rstmodule("ModuleID")
txtmodulename.Value = rstmodule("ModuleName")
txtmoduleshortcode.Value = rstmodule("ModuleShortCode")
cmblevel.Value = rstmodule("Level")
cmbsemester.Value = rstmodule("Semester")
cmbcatpoints.Value = rstmodule("CATPoints")
Active.Value = rstmodule("Active")
txttype.Value = rstmodule("Type")
End If
End Sub
This code works perfectly on three of my other forms. They populate data from different tables though. Could the problem have anything to do with the table being called Module? Because I've used [ ] in the SQL statement but still no joy? Any help would be appreciated. Thanks.

Inside the SQL string, you need to either :
a) change your table name to not be a keyword
b) surround all references in the SQL to Module with square brackets
c) use an alias: Select m.* FROM [Module] as m
d) change your table name to not be a keyword.

Related

"NotOnList" event not recognizing that new data has, in fact, been added

This used to work but now it doesn't. Did Microsoft change something?
I'm attempting to understand the behavior of a combo box in MS Access. I created a table named "Colors" with 2 fields: ID (Autonumber, primary key) and Color (short text). I made a form with a combobox with "LimitToList" set to Yes. The Row Source is the table "Colors". For the NotInList event I have the following code:
Private Sub Colors_NotInList(NewData As String, Response As Integer)
Dim rst As DAO.Recordset
If MsgBox(NewData & " is not in list. Add it?", vbOKCancel) = vbOK Then
Response = acDataErrAdded
Set rst = CurrentDb.OpenRecordset("Colors")
With rst
.AddNew
!Color = NewData
.Update
End With
Else
Response = acDataErrContinue
ctl.Undo
End If
End Sub
If I enter a color not in the table I get the prompt to add it to the list. On clicking OK I get the Access error that I must select an item on the list. The new color I just entered does appear on the list and if I select it everything works fine. But I didn't used to have this second step of selecting it after it's been entered.
I've spent way to much time on what should be a simple task. Can anyone help? Thanks!

Run-Time error 3075 Access Syntax Error for combobox Search in Access

I am learning about how to create a searchbox with combo box. I was learning with a video in youtube :
Access: How to Create Search Form Using Combo box Part 1
However, when I do my code it doesn't work. :/ I get the Run-Time error 3075 Access Syntax Error.
Private Sub cboVendorSearch_AfterUpdate()
Dim MyVendor As String
MyVendor = "Select * from Vendors where ([vend_name] = " & Me.cboVendorSearch & ")"
Me.Invoices_subform.Form.RecordSource = MyVendor
Me.Invoices_subform.Form.Requery
End Sub
Assuming vend_name is a text field, need apostrophe delimiters.
MyVendor = "SELECT * FROM Vendors WHERE [vend_name] = '" & Me.cboVendorSearch & "';"
Instead of setting RecordSource, an alternative is to set Filter property.
Me.Invoices_subform.Form.Filter = "[vend_name] = '" & Me.cboVendorSearch & "'"
Me.Invoices_subform.Form.FilterOn = True
Would probably be better to use vendor ID for search criteria. Explore multi-column combobox where the ID field is a hidden column but combobox uses the hidden column for its Value yet displays vend_name to user.

Open form to view related records if they exist or open blank form otherwise

Hi I have a form called frmGeneralInformation where the main data is inputted about a book. Then I want a button that opens a form called frmFolio which shows the information about each page in the book. If records about the folios of the book already exist, the existing records should be shown with the option to add more folios. Otherwise a blank frmFolio should be created.
This is my VB code:
Private Sub FolioForm_Click()
Dim Found As Boolean
Found = Not IsNull(DLookup("SurveyID", "tblGenInfo_Folio", "SurveyID = " & .SurveyID))
If Found = True Then
Dim recordID As Integer
recordID = Me.FolioID
DoCmd.OpenForm "frmFolio", , , "FolioID = " & FolioID
Else
DoCmd.OpenForm "frmFolio"
End Sub
But I am getting this error:
Invalid or unqualified error
This is the relationship between the tables:

Updating row in database using vb.net

I am trying to update and save a row of a database table. I have used a version of this code to just populate a GridView and it works, so I am assuming it has something to do with my SQL statment; I do not get an error, the table just does not update. On the page load event I have the textboxes being populated by the information of the row, and I have a global variable, named 'temp', that will save the title of the row so I can use it in the button's click event. The error I am getting states that I have not given a value for one of my required parameters. My Locals tab on the debugger shows that every variable has a value, though the one I try to update is not the new data but still the old data.
I have looked at several examples and I cannot find the problem though. Thank you for any assistance.
Protected Sub btnSave_Click(sender As Object, e As EventArgs)
Dim strTitle As String = txtTitle.Text
Dim strConsole As String = txtConsole.Text
Dim strYear As String= txtYear.Text
Dim strPurchase As String = calDate.SelectedDate.ToString
Using con As OleDbConnection = New OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "DATA SOURCE=" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "App_Data", "db1.accdb"))
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.CommandText = Convert.ToString("UPDATE Video_Games SET Title = #title, Console = #Console, Year_Released = #Year_Released, Purchase = #Purchase WHERE Title=" & temp)
cmd.Connection = con
cmd.Parameters.AddWithValue("#Title", strTitle)
cmd.Parameters.AddWithValue("#Console", strConsole)
cmd.Parameters.AddWithValue("#Year_Released", strYear)
cmd.Parameters.AddWithValue("#Purchase", strPurchase)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
Server.Transfer("Form.aspx", True)
End Sub
I have also tried the have my where statement as: WHERE Title='" & temp & "'") Though this does not work either.
This is the details of the Error message
I changed you commandText as seen below and created a blank database with a table named just like yours and the update worked
cmd.CommandText = "UPDATE Video_Games SET Title = #title, Console = #Console, Year_Released = #Year_Released, Purchase = #Purchase WHERE Title='" & temp & "'"
I set my variable for Title = Super Mario Bros and then the temp variable to Wario World. I had a record in my database with the title of Wario World, and running the update changed the title to Super Mario Bros.
Check if you temp variable is different from your #title variable. Also check that you have the record int the table for your temp variable title
Thank you all for your assistance, This is such a wonderful community.
The problem, I found out, does not even have to do with the button's click event, it had to do with the page load event. Since on page load the row's information is loaded and populated into the textboxes, when the button is clicked to update the fields, the page load event triggers again and reloads the old information into fields, essentially saving the old information instead of the new. My fix was to create an If Not IsPostBack Then statement that encapsulates my on page load code. Therefore the code does not get saved when the button is pressed. Another this, I did not need the temp variable, using WHERE Title='" + strTitle + "'" worked. Hopefully this helps other people stuck on a similar problem!
Using dates in a where clause is always ify as they are floating point numbers and may not match equally. I'd try and round them or convert them to strings before comparison, e.g. something along these lines:
UPDATE Video_Games SET Title = #title, Console = #Console, Year_Released = #Year_Released, Format(Purchase, ""m/d/yyyy"") = Format(#Purchase, ""m/d/yyyy"") WHERE Title = #Title

Can not update List Box Selected Collection in code

I have a list box on a form being populated from a query, with items selected on basis of matching a delimited list. So sSystemString equals something like "A;B;C"
Then I load records A,B,C,D,E,F from the SQL Server DB and only A,B,C should be selected.
Is there a native way to do this in MS Access (2010). I'm using an ADP in this case.
I'm doing it via code but I can't the selected property does not reflect my changes, nor does the form.
Here's my code:
Dim rs As New ADODB.Recordset
Dim sSystemString As String
If Not IsNull(Me.OpenArgs) Then sSystemString = Me.OpenArgs
' Load this list box with SRC Systems
Call rs.Open("SELECT DISTINCT System FROM dbo.System WHERE System IS NOT NULL", _
CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly)
Do Until rs.EOF
lstSrcSystems.AddItem (rs.Fields(0))
If InStr(sSystemString, rs.Fields(0)) > 0 Then
lstSrcSystems.Selected(lstSrcSystems.ListCount - 1) = True
End If
rs.MoveNext
Loop
My code definitely hits the lstSrcSystems.Selected(lstSrcSystems.ListCount - 1) = True line.
After running this line, inspecting the property in the immediate window still returns 0 (it doesn't change). On the form, the item is also not selected.
UPDATE: I just checked my code again and now it is being updated, but the next AddItem apparently unselects it again.
I suspect I have some weird combination of properties that make this read only, but I can select items interactively, and indeed when I extract the selected items back off in code, the Selected property works as expected - i.e. I select an item on the form and it reflected in this property.
The form is unbound and is called from a button on another form with this code:
DoCmd.OpenForm "fSiteList", acNormal, , , acFormEdit, acDialog, Me.SRCSystems
The problem was actually that lstSrcSystems.AddItem (rs.Fields(0)) was resetting the Selected state. I can't find any mention of this behaviour or how to turn it off. I altered my form as follows:
Form / Data properties all blank (unbound)
List Control / Data / Control Source: blank
List Control / Data / Row Source: SELECT statement populating my list
This has the effect of populating the list but not binding the list or form to anything. (I found that binding it stopped me interactively editing data on it)
Form_Load code behind the form was changed to select already existing items:
Private Sub Form_Load()
Dim sSystemString As String
Dim iIndex As Integer
' List is bound to site list (from connections)
' Highlight those that are listed
If Not IsNull(Me.OpenArgs) Then sSystemString = Me.OpenArgs
iIndex = lstSrcSystems.ListCount
Do While iIndex > 0
If InStr(sSystemString, lstSrcSystems.ItemData(iIndex)) > 0 Then
lstSrcSystems.Selected(iIndex) = True
End If
iIndex = iIndex - 1
Loop
End Sub
I'm still curious to know whether there is a more 'built in' way to achieve this: edit a delimited string field.