Invalid use of Me keyword - ms-access

This code is a function and not a private subroutine. I'm suddenly getting this error with the Me.[field name here]. I'm not getting that error in my other code, just in this one. Here's my full code without the boring end part, but I'm getting the error starting from the line:
Me.assignedby.Column(1)
Public Function AssignNullProjects() As Long
Dim db As dao.Database
Dim rs As dao.Recordset
Dim strSQL As String
assignedby = TempVars("user").Value
Set db = CurrentDb
strSQL = "SELECT CFRRRID FROM CFRRR WHERE assignedto Is Null"
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
If Not rs.BOF And Not rs.EOF Then
While Not rs.EOF
strSQL = "UPDATE CFRRR SET assignedto = " & GetNextAssignee & ", assignedby = " & Me.assignedby.Column(1) & ", Me.Dateassigned = #" & Now & "#, Me.actiondate = #" & Now & "#, Me.Workername = " & _
Me.assignedto.Column(0) & ", Me.WorkerID = " & Me.assignedto.Column(0) & " WHERE CFRRRID = " & rs!CFRRRID
db.Execute strSQL, dbFailOnError
rs.MoveNext
Wend
End If
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
What could be the possible reason for the above-stated error, and how it could be removed?

Put that code in the form's code module. When you try to use Me in a standard module, you will always get that "Invalid use of Me keyword" complaint.
Check out the "Invalid use of Me keyword" and "Me <keyword>" topics in Access' help system for further details.

Related

Openrecordset With Multiple Tables, Access 2016

I am getting an "Object variable or With block variable not set (Error 91)" error with the following code:
Dim db As Database
Dim rs As Recordset
Private Sub Form_Load()
Dim mySQL As String
mySQL = "SELECT Tuteurs.ID_Tuteur, Tarifs_17_18.*, Paiements_17_18.* " & _
"FROM (Tuteurs INNER JOIN Tarifs_17_18 ON Tuteurs.ID_Tuteur = Tarifs_17_18.TuteurID_Trf) " & _
"INNER JOIN Paiements_17_18 ON Tuteurs.ID_Tuteur = Paiements_17_18.TuteurID_Pmt " & _
"WHERE ID_Tuteur =" & [Forms]![Eleves]![TuteurID_Elv]
Set db = CurrentDb
Set rs = db.OpenRecordset(mySQL, dbOpenDynaset, dbSeeChanges)
rs.MoveFirst
End Sub
Private Sub btn_Enregistrer_Click()
Dim totIns As Integer
totIns = DSum("Montant", "Paiements_17_18", "[Mois_Regle]='Inscription'")
If totIns = rs!Tarif_Inscription Then
MsgBox "Yes" & totIns & " = " & rs!Tarif_Inscription
Else
MsgBox "No" & totIns & " # " & rs!Tarif_Inscription
End If
End Sub
totIns is working very well but rs!Tarif_Inscription is the missing object variable.
[Tarif_Inscription] is a field in the [Tarifs_17_18] Table.
Any Help Please?
I Found the Solution,
My recordset is not in scope and My variables are declared outside My procedure.
Solution found by #Moke123.

VBA Access Getting Runtime Error 3144 on previously working event

I have an issue that has developed while modifying an update event that previously had been working. I am now getting a Runtime Error 3144, "Syntax error in UPDATE statement." When I go to debug the following line of code is flagged.
Set qdf = db.CreateQueryDef(vbNullString, strUpdate)
This function previously was working as it it was meant to in creating a SQL string to run an Update command. However I needed to adapt this same function to a different but mostly similar form.
I have included the complete code below for review and could use some assistance in spotting whatever little detail I missed/messed up in the transfer.
Private Sub btnEntEdt_Click()
Dim strUpdate As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
strUpdate = "UPDATE EntList AS e" & vbCrLf & _
"SET e.BusinessUnit = pBusinessUnit, " & _
"e.EntityID = pEntityID, " & vbCrLf & _
"e.EntityName = pEntityName, " & vbCrLf & _
"e.Location = pLoc, " & vbCrLf & _
"e.Client = pCli, " & vbCrLf & _
"e.Dept = pDept, " & vbCrLf & _
"WHERE e.EntityID = pEntityID;"
Debug.Print strUpdate
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strUpdate)
qdf.Parameters("pBusinessUnit") = Me.cboBUnit.Value
qdf.Parameters("pEntityName") = Me.txtEntName.Value
qdf.Parameters("pEntityID") = Me.txtEntID.Value
qdf.Parameters("pLoc") = Me.cboLoc.Value
qdf.Parameters("pCli") = Me.cboClient.Value
qdf.Parameters("pDept") = Me.cboDept.Value
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
Me.lstEntName.Requery
End Sub
You were wise to include Debug.Print strUpdate. Examine its output ...
UPDATE EntList AS e
SET e.BusinessUnit = pBusinessUnit, e.EntityID = pEntityID,
e.EntityName = pEntityName,
e.Location = pLoc,
e.Client = pCli,
e.Dept = pDept,
WHERE e.EntityID = pEntityID;
That statement triggers an error because of the comma at the end of the SET clause.
e.Dept = pDept,
^ here
Eliminate that comma, test the revised UPDATE statement in the query designer, and once you have it working correctly, modify your VBA code to produce the same statement text.
Or you could save the working version as a named query, qryUpdateEntList, and then reference the named query from your VBA code instead of re-creating the statement text at run time.
Set qdf = db.QueryDefs("qryUpdateEntList")
Apart from the syntax error, this combination looks wrong to me ...
SET e.EntityID = pEntityID
WHERE e.EntityID = pEntityID
Because of the WHERE clause, the UPDATE will only affect rows where EntityID = pEntityID. So there is no need to SET EntityID = pEntityID; they are already equal.

Access VBA to update Access table from SQL Server table source

I have created the code below to test whether I can run a query and retrieve a data from an SQL server table. And so far I can return the result using a MessageBox, but somehow I just don't know how to use this connection to update the table inside this Access file. Basically I want to use this as a front end file. Then, when the form is open it will automatically update the table inside this access file and load the data to the combo box as a list. I tried searching it here and read many discussions here and in Google but currently I can't find the right solution.
Option Compare Database
Sub LocalServerConn_Test()
Set conn = New adodb.Connection
Set rst = New adodb.Recordset
strDBName = "DataSet"
strConnectString = "Provider = SQLOLEDB.1; Integrated Security = SSPI; " & _
"Initial Catalog = " & strDBName & "; Persist Security Info = True; " & _
"Worksation ID = abc123;"
conn.ConnectionString = strConnectString
conn.Open
strSQL = "SELECT DISTINCT dbo.abc.abc123 FROM dbo.abc"
rst.Open Source:=strSQL, ActiveConnection:=strConnectString, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic
If rst.RecordCount = 0 Then
MsgBox "No records returned"
Else
rst.MoveFirst
Do While Not rst.EOF
MsgBox rst.Fields("abc123").Value
rst.MoveNext
Loop
End If
conn.Close
rst.Close
End Sub
You should be able to use code very similar to this:
Dim cdb As DAO.Database
Set cdb = CurrentDb
cdb.Execute _
"DELETE FROM LocalTable", _
dbFailOnError
cdb.Execute _
"INSERT INTO LocalTable (abc123) " & _
"SELECT DISTINCT abc123 " & _
"FROM " & _
"[" & _
"ODBC;" & _
"Driver={SQL Server};" & _
"Server=.\SQLEXPRESS;" & _
"Database=DataSet;" & _
"Trusted_Connection=yes;" & _
"].[dbo.abc]", _
dbFailOnError
Set cdb = Nothing
You can just keep the combo box bound to [LocalTable] and the updated values from the SQL Server table should appear.

Is there a faster alternative to DLookup?

I'm using DLookup to search for a field in a table. It runs correctly, but is slow. Is there anything I can do to speed it up?
Here's my existing code:
Private Sub cmdLogin_Click()
strUserLevel = ""
If IsNull(Me.cmbUserName) Or Me.cmbUserName = "" Then
MsgBox "You must enter a User Name.", vbOKOnly, "Required Data"
Me.cmbUserName.SetFocus
Exit Sub
End If
If IsNull(Me.txtPassword) Or Me.txtPassword = "" Then
MsgBox "You must enter a Password.", vbOKOnly, "Required Data"
Me.txtPassword.SetFocus
Exit Sub
End If
'strUserName = cmbUserName.Value
If Me.txtPassword.Value = DLookup("Password", "tableUser", "[lngEmpID]=" & Me.cmbUserName.Value) Then
lngMyEmpID = Me.cmbUserName.Value
strUserLevel = DLookup("Department", "tableUser", "[lngEmpID]=" & Me.cmbUserName.Value)
strUserName = DLookup("User_Name", "tableUser", "[lngEmpID]=" & Me.cmbUserName.Value)
boolInventoryMDL = DLookup("Inventory", "tableDepartment", "[Department]=""" & strUserLevel & """")
boolDispositionMDL = DLookup("Disposition", "tableDepartment", "[Department]=""" & strUserLevel & """")
boolReviewCloseMDL = DLookup("Review", "tableDepartment", "[Department]=""" & strUserLevel & """")
boolAdministratorMDL = DLookup("Administrator", "tableDepartment", "[Department]=""" & strUserLevel & """")
boolUserListMDL = DLookup("UserList", "tableDepartment", "[Department]=""" & strUserLevel & """")
boolUserLevelMDL = DLookup("UserLevel", "tableDepartment", "[Department]=""" & strUserLevel & """")
If strUserLevel = "Superuser" Then
MsgBox "Welcome back Superuser! You can access all the modules here..", vbOKOnly, "Caution"
Else
MsgBox "Welcome! Login Success!", vbOKOnly, "Login Page"
End If
DoCmd.Close acForm, "frmLogin", acSaveNo
DoCmd.OpenForm "frmModule"
Else
MsgBox "Password Invalid. Please Try Again", vbOKOnly, "Invalid Entry!"
Me.txtPassword.Value = ""
Me.txtPassword.SetFocus
End If
End Sub
I don't believe the problem is due to inherent slowness of DLookup. Rather the problem is that the code uses so many of them.
Open one recordset based on a query of tableUser and take the values you need from that recordset. Then open a second recordset from a query of tableDepartment and get your remaining values.
Dim db As DAO.database
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strSelect As String
strSelect = "SELECT u.Password, u.Department, u.User_Name" & vbCrLf & _
"FROM tableUser AS u WHERE u.lngEmpID = [which_EmpId];"
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strSelect)
qdf.Parameters("which_EmpId") = Me.cmbUserName
Set rs = qdf.OpenRecordset(dbOpenSnapshot)
If Not rs.EOF Then
If rs![Password] = Me.txtPassword Then
strUserLevel = rs!Department
strUserName = rs!User_Name
rs.Close
' open another recordset from a query of tableDepartment
' to retrieve your bool????? values
End If
End If
In that abbreviated sample, I used a temporary QueryDef for the parameterized SELECT query. However you would be better of to save that SQL as a named query, perhaps qryFetchUserData. Then at run time, instead of recreating the query each time, you could simply open the saved query.
Set qdf = db.QueryDefs("qryFetchUserData")
For optimum performance, you should add indexes on tableUser.lngEmpID and tableDepartment.Department if they're not already indexed.

Instructing ADODB Recordset to use SQL Server current timestamp

I am attempting to write a number of records back to the database from a VB6 application using ADO. The records were read in from the database into an ADODB.Recordset and subsequently updated. I would like to be able to have each record in the set use the current date and time of the database server because I have no confidence that all our machines are time-synchronized. Is there a way to do this without having to query the database for CURRENT_TIMESTAMP (or something similar)? Ideally I'm hoping for some sort of flag that I can set the field value to so that the Recordset works this out on the database server.
See the question in my prototype code below (within the while-loop).
Dim oConn As ADODB.Connection
Dim oRs As ADODB.Recordset
Dim sSQL As String
Dim sColumnName1 As String: sColumnName1 = "UserNID"
Dim sColumnName2 As String: sColumnName2 = "Username"
Dim sColumnName3 As String: sColumnName3 = "LastLoginDTM"
' Open a connection.
Set oConn = New ADODB.Connection
oConn.Open 'my connection string was here
' Make a query over the connection.
sSQL = "SELECT TOP 10 " & sColumnName1 & ", " & sColumnName2 & ", " & sColumnName3 & " " & _
"FROM theTable"
Set oRs = New ADODB.Recordset
oRs.CursorLocation = adUseClient
oRs.Open sSQL, oConn, adOpenStatic, adLockBatchOptimistic, adCmdText
oRs.MoveFirst
While Not oRs.EOF
oRs.Fields(sColumnName3).Value = '-=-=-=-=-What do I put here???-=-=-=-=-
oRs.MoveNext
Wend
' Close the connection.
oConn.Close
Set oConn = Nothing
You could use the TSQL GetDate() Function
Change your Select to:
sSQL = "SELECT TOP 10 " & sColumnName1 & ", " & sColumnName2 & _
", " & sColumnName3 & ", GETDATE() AS ServerTimeStamp " & _
"FROM theTable"
Then, your code could be:
While Not oRs.EOF
oRs.Fields(sColumnName3).Value = oRS.Fields("ServerTimeStamp").Value
oRs.MoveNext
Wend