this code is to populate textboxes in form where sql query is fatching data from table RR_info on the behalf of hr_id. it compare hr_id of rr_info with the bounded value of listbox.
Private Sub Form_Load()
Dim SQL As String
Dim db As Database
Dim rs As DAO.Recordset
SQL = "select * from RR_info where hr_id = " & Forms![hhrrr]![List38] & ";"
Set db = CurrentDb
Set rs = db.OpenRecordset(SQL)
'DoCmd.RunSQL SQL 'at this point it gives me error 2342
Me.RR_ID.value = rs!RR_ID
Me.HR_ID.value = rs!HR_ID
Me.Room_No.value = rs![Room No]
Me.No_of_Beds.value = rs!No_of_Beds
Me.Room_Category.value = rs!Room_Category
Set rs = Nothing
Set db = Nothing
End Sub
You dont need string "DoCmd.RunSQL SQL".
And it is better to use .Value insted of .Text
Related
I am trying to retrieve records from a table in access using VBA. So far I have this simple function:
Private Function GNCN() As String
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim cm As ADODB.Command
Dim strSQL As String
Dim intYD As Integer
Set cn = CurrentProject.Connection
'cn.CursorLocation = adUseClient
rs.CursorLocation = adUseClient
rs.LockType = adLockReadOnly
intYD = 16
strSQL = "SELECT DCN FROM tblDCD WHERE (DCN like '" & intYD & "*')"
Set rs = cn.Execute(strSQL)
Debug.Print rs.RecordCount
Set rs = Nothing
Set cm = Nothing
Set cn = Nothing
End Function
When I run this, I don't get any records returned.
However if I take the SQL query:
SELECT DCN FROM tblDCD WHERE (DCN like '16*')
and run this within Access' query builder, I get around 912 records returned, so I know I am able to retrieve the records and that the query itself appears to be correct.
The table is simple data which consists of string values such as (in the DCN column):
"13000"
"17001"
"16003"
Around 38000 in total so I shaln't print them all here...
Does anyone know why this will work via the query builder but not via VBA?
Thanks
Appear to be mixing DAO and ADODB. Consider:
Private Function GNCN() As String
Dim rs As DAO.Recordset
Dim strSQL As String
Dim intYD As Integer
intYD = 13
strSQL = "SELECT DCN FROM Rates WHERE DCN like '" & intYD & "*';"
Set rs = CurrentDb.OpenRecordset(strSQL)
rs.MoveLast
Debug.Print rs.RecordCount
Set rs = Nothing
End Function
I am using the below code to track changes on a form and it works fine.
However, I am trying to use it on my main form to record just the date/time that someone clicks a button However I get the following error:
You entered an expression that has no value
The debug takes me to this:
rs!PriorInfo = Screen.ActiveControl.OldValue
My code
Function TrackChanges()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
Dim strCtl As String
Dim strReason As String
' strReason = InputBox("Reason For Changes")
strCtl = Screen.ActiveControl.Name
strSQL = "SELECT Audit.* FROM Audit;"
Set db = CurrentDb()
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
If rs.RecordCount > 0 Then rs.MoveLast
With rs
.AddNew
rs!FormName = Screen.ActiveForm
rs!ControlName = strCtl
rs!DateChanged = Date
rs!TimeChanged = Time()
rs!PriorInfo = Screen.ActiveControl.OldValue
rs!NewInfo = Screen.ActiveControl.Value
rs!CurrentUser = fOSUserName
' rs!Reason = strReason
.Update
End With
Set db = Nothing
Set rs = Nothing
End Function
I assume I need to tell it to accept null values but unsure how?
Nz(Screen.ActiveControl.OldValue) will return an empty string instead of a null value.
Nz(Screen.ActiveControl.OldValue,"<Null>") if PriorInfo is text and you want to record it was null.
Nz(Screen.ActiveControl.OldValue,-1) if PriorInfo is numeric and -1 is a safe "null" number.
I'm trying to open a record set using a SQL string. I get run time error 3061 "Too Few Parameters." any help would be appreciated.
Dim stAppName As String
Dim stURL As String
Dim rst As Recordset
Dim dbs As Database
Dim stringToSearch As Integer
Dim strSQL As String
Set dbs = CurrentDb
stringToSearch = InputBox("What is your route #?", "Enter route #: ")
strSQL = "SELECT ESRP.* FROM ESRP WHERE ESRP.Route=stringToSearch"
Set rst = dbs.OpenRecordset(strSQL)
Please change the code line of strSQL as follows, as suggested by Fionnuala you need to use variable outside the quotes.
Assuming Route field is Text data type, we need to put single quote for strings, if its number no single quote, for dates put # instead of single quote
strSQL = "SELECT ESRP.* FROM ESRP WHERE ESRP.Route='" & stringToSearch & "'"
It's a little sample, maybe it can help you
Public Function fn_SQL_dbOpenRecordset(Optional vsql As String = "") As Recordset
Dim dbs As DAO.Database
Dim rs As Recordset
On Error GoTo END_CODE
'Set the database
Set dbs = CurrentDb
Set rs = dbs.OpenRecordset(vsql, dbOpenForwardOnly) 'you can use: dbOpenDynamic; dbOpenSnapshot; dbOpenTable
Set fn_SQL_dbOpenRecordset = rs
Exit Function
END_CODE:
Set fn_SQL_dbOpenRecordset = Nothing
End Function
Public Sub Program_Test()
On Error GoTo ERROR_SUB
Dim rs As Recordset
Dim sName As String
sName = "Joe"
sName = "'" & sName & "'" 'WARNING: BE CAREFUL WITH SQL INJECTION !!! Google it
Set rs = fn_SQL_dbOpenRecordset("select * from table1 d where PersonName = " & sName)
Dim i As Long
i = 0
While Not rs.EOF
Debug.Print rs(0).Value & " - " & rs(1).Value
rs.MoveNext
Wend
ERROR_SUB:
On Error Resume Next
If Not rs Is Nothing Then rs.Close
Set rs = Nothing
End Sub
I have wrote this code to populate the listbox through VBA Code but its not working. i cant understand what's wrong with it.
Private Sub Form_Load()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strsql As String
strsql = "select hotel_id, hotel_name from Hotels"
Set db = CurrentDb
Set rs = db.OpenRecordset(strsql)
Me.List0.RowSource = hotels 'where hotels is name of table
Me.List0.ColumnWidths = "1 in; 2 in"
End Sub
Change
Me.List0.RowSource = hotels
to
Me.List0.RowSource = strsql
You're trying to set your list rowsource to a table, which Access doesn't understand. it wants a SQL string, and "strsql" is that string.
You could also just set it directly like:
Me.List0.RowSource = "select hotel_id, hotel_name from Hotels"
The following code executes a stored procedure pass through query. The paramter is received fromthe form and is passed to the stored procedure. The error says that it is an invalid SQL Statement. I need to know if the code is right and how you connect to the database. The results are returned in a record set. Thanks!
Private Sub Command10_Click()
Dim rs1 As DAO.Recordset
Dim DB As Database
Dim Q As QueryDef
Dim strSQL As String
Set DB = CurrentDb()
Set Q = DB.QueryDefs("Call_SP")
strSQL = "execute dbo.ix_spc_planogram_match " & [Forms]![start]![Selection]![cat_code]
Q.ReturnsRecords = True
Q.SQL = strSQL
Set rs1 = DB.OpenRecordset(strSQL)
Do While Not rs1.EOF
Debug.Print rs1.Fields.Item("POG_DBKEY").Value = "POG_DBKEY"
Debug.Print rs1.Fields.Item("COMP_POG_DBKEY").Value = "COMP_POG_DBKEY"
Debug.Print rs1.Fields.Item("CURR_SKU_CNT").Value = "CURR_SKU_CNT"
Debug.Print rs1.Fields.Item("COMP_SKU_CNT").Value = "COMP_SKU_CNT"
Debug.Print rs1.Fields.Item("SKU_TOTAL").Value = "SKU_TOTAL"
Debug.Print rs1.Fields.Item("MATCHD").Value = "MATCHD"
rs1.MoveNext
Loop
rs1.Close
Set rs1 = Nothing
Set rs1 = Nothing
End Sub
CurrentDB is MS Access, but you are executing an SQL Server stored procedure. You need to execute against a connection to the server.
For example:
Dim objcon As New ADODB.Connection
scn = "Provider=sqloledb;Data Source=ServerName;" _
& "Initial Catalog=DBNAME;User Id=USERNAME;Password=Password;"
objcon.Open scn
Set rs = objcon.Execute