Access VBA Recordset - sql

I have an access database that contains a table with employee information. My issue is that I want to loop through another table in order to determine if a specific characteristic is true or false first, then display all the records that are true in a continous form. It still populates all the records not just the ones that are true. Please see code below.
Private Sub RunQuery_Click()
Dim strSQL As String
Dim dba As Database
Dim tbl As Recordset
Dim Code As String
Dim status As String
Set dba = CurrentDb
strSQL = "SELECT DISTINCT EmployeeName,SSN,Location,SystemAssignedPersonID FROM dbo_tbl_Random "
strSQL = strSQL & "WHERE MenuUsed = 'Random' ORDER BY Location,EmployeeName"
Set tbl = dba.OpenRecordset(strSQL, dbOpenDynaset, dbSeeChanges)
With tbl
.MoveFirst
If tbl.EOF Then
MsgBox "There are no employees on Random at this time.", , "Oops! Try Again"
Else
Do Until tbl.EOF
status = getEmpStatusID(tbl!SystemAssignedPersonID)
If status = "A" Then
Set Me.Recordset = tbl
.MoveNext
Else
.MoveNext
End If
Loop
End If
End With
Set tbl = Nothing
Set dba = Nothing
End Sub
The getEmpStatusID is a seperate function that is not giving me trouble. It looks up the Employee ID to get the information and returns it fine.
Thanks for the help!

I think you're most of the way there already. Depending on what getEmpStatusID does you can do something like this
SELECT DISTINCT EmployeeName,SSN,Location,T.SystemAssignedPersonID
FROM dbo_tbl_Random R
Inner JOin Table_Where_Status_Is_Found as T
on T.SystemAssignedPersonID = R.SystemAssignedPersonID
WHERE MenuUsed = 'Random' and T.SystemAssignedPersonID = 'A'
ORDER BY Location,EmployeeName
Use that as the rowsource for your form and don't use VBA. Your form will not be updatable because you used distinct, though. Is that necessary?

Related

How to iterate through a recordset and do a lookup

I need to iterate through a record set but when it gets to a user name field I want to do a lookup to a user ID table to pull in the actual name. Then end loop when cusip column is null?
You can iterate over a recordset which already includes the actual name by opening a recordset for a SQL statement such as:
select * from tblImport inner join tblUser on tblImport.UserID = tblUser.ID
The code might look something like:
Sub MySub()
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim flg As Boolean
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("select * from tblImport inner join tblUser on tblImport.UserID = tblUser.ID")
With rst
If Not .EOF Then
.MoveFirst
Do Until .EOF Or flg ' No short-circuit evaluation in VBA
flg = IsNull(!Cusip)
.MoveNext
Loop
End If
.Close
End With
Set rst = Nothing
Set dbs = Nothing
End Sub
You'll need to change the field & table names to suit your data.
You haven't stated what you actually want to do with the data within the loop.

VBA check if distinct values from 2 fields match

I'm VERY new to VBA but have some coding experience so I'm slowly starting to learn. I have two tables in my access database that each have one field that is the same. One table is a distinct list of the possible values ("TOSITEXREF")that could show up in the same field on the other table ("Trans_Earned"). This function I am trying to create will run in a macro to figure out whether or not the data that is being appended via queries has an instance in the ToLocn field that is not on the list of possible values. Here is what I have so far, but is not working:
Function TESTING()
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("TransEarned")
Dim rs2 As DAO.Recordset
Set rs2 = CurrentDb.OpenRecordset("TOSITEXREF")
Dim cond1A As Boolean
cond1A = (rs.Fields("ToLocn") = rs2.Fields("ToLoc"))
If cond1A Then
DoCmd.OpenQuery "Earns", acViewNormal, acEdit
Else
DoCmd.CancelEvent
MsgBox "Unknown ToLocation, Please Update TOSITEXREF File to acccount for new location", vbOKOnly, "NEW LOCATION"
End If
Set rs = Nothing
Set rs2 = Nothing
End Function
Final VBA example that will return a value in the Loc field from table1 that does not show up in the Loc field of Table2:
Function Validate()
Dim sql As String
Dim rs As DAO.Recordset
sql = "SELECT Table1.Loc FROM Table1 LEFT JOIN Table2 ON Table1.Loc = Table2.Loc WHERE (((Table2.Loc) Is Null))"
Set rs = CurrentDb.OpenRecordset(sql)
If (rs.RecordCount = 0) Then
MsgBox "WORKS", vbkokonly, "WORKS"
Else
MsgBox "DOES NOT WORK", vbkokonly, "DOES NOT WORK"
Set rs = Nothing
End If
End Function

Updating table with VBA

I have been struggling with getting this code to work for a few days. If you could offer any solutions I would really appreciate it.
Private Sub Command0_Click()
If IsNull(NewSupBox.Value) Or IsNull(NewNumberBox.Value) Then
MsgBox ("All fields must be filled")
GoTo ErrorExit
End If
If Not IsNull(DLookup("SupplierNumber", "SupGenInfo ", "SupGenInfo.SupplierNumber =" & NewSupBox)) = Then
MsgBox ("This supplier number already exists. You can edit the current record on the Edit supplier page.")
GoTo ErrorExit
End If
Dim db As Database
Dim rec As Recordset
Set db = CurrentDb
Set rec = db.OpenRecordset("select * from SupGenInfo")
rec.AddNew
rec("SupplierNumber") = Me.NewSupBox.Value
rec("SupplierName") = Me.NewNameBox.Value
rec.Update
Set rec = Nothing
Set db = Nothing
MsgBox "Records added successfully."
ErrorExit:
End Sub
Edit: Forgot to mention that I am not getting any error message. The command will simply not add a new record to my table.
Edit2: The code above will output the msg "Records Added Successfully" when i remove the following block of code.
Dim db As Database
Dim rec As Recordset
Set db = CurrentDb
Set rec = db.OpenRecordset("SupGenInfo")
rec.AddNew
rec("SupplierNumber") = Me.NewSupBox
rec("SupplierName") = Me.NewNameBox
rec.Update
Set rec = Nothing
Set db = Nothing
It is when this code is included that my command click becomes unresponsive.
I believe, you are reading a table (for display purposes) with your select * ... statement, then you're adding a new record to that list rather than the actual database. When you open OpenRecordset, just supply the table name, not a whole SQL query shebang...
I created a new table, so edit this code to match your parameters/values, otherwise this has been tested to work:
Dim db As Database
Dim rec As Recordset
Set db = CurrentDb
Set rec = db.OpenRecordset("Table1")
rec.AddNew
rec("Field1") = 1234
rec("Field2") = "blah2"
rec("Field3") = "blah3"
rec.Update
Set rec = Nothing
Set db = Nothing
Hope this helps.

VBA access run sql check row count

I'm trying to display a field on a form depending on the results of an sql query. Since I don't know vba in access I'm struggling and don't know where I am going wrong. Help will be greatly appreciated.
Dim RecordSt As Recordset
Dim dBase As Database
Dim stringSQL As String
Set dBase = CurrentDb()
stringSQL = "SELECT * FROM Table1 WHERE ID = 2"
DoCmd.RunSQL (stringSQL)
If RecordSt.Fields.Count > 0 Then
Me.Other.Visible = True
Else
Me.Other.Visible = False
End If
If DCount("*", "table1", "id = 2") > 0 Then
Me.Other.Visible = True
Else
Me.Other.Visible = False
End if
or even quicker:
Me.Other.Visible = (DCount("*", "table1", "id = 2") > 0)
There are many problems in your code.
First of all Docmd.RumSQL(stringSQL)
do not return nothing, and it is not related to your recordset RecordSt.
Also RecordSt.Fields.Count will count the FIELDS of your table and not the number of RECORDS selected.
This is a solution using ADODB. You probably have to add the reference to ADO (you can choose another version if you don't have 6.1) in your Tools->Reference menu from your VBA editor:
Dim rst As new ADODB.Recordset
Dim stringSQL As String
stringSQL = "SELECT * FROM Table1 WHERE ID = 2"
rst.Open SQL, CurrentProject.AccessConnection
If rst.RecordCount > 0 Then
Me.Other.Visible = True
Else
Me.Other.Visible = False
End If

What if the SQL statement does not find any 'matches' in the table?

Using MS Access, I tried to run an SQL statement but I can't make it work in the case that the table has no records yet. Will appreciate the help! Thanks!
Public Function GetReferenceID(RefCode As String) As Integer
Dim RefID As Integer
Dim rec As Recordset
Call connectDB
sSQL = "select RefID from Exceptions where RefCode = '" & RefCode & "'"
Set rec = CurrentDb.OpenRecordset(sSQL)
If (Not rec.EOF And Not rec.BOF) Then
RefID = rec.RecordCount + 1
Else
RefID = 1
End If
GetReferenceID = RefID
End Function
Private Sub RefCode_Change()
Dim tr As Transactions, rID As Integer
Set tr = New Transactions
tr.GetReferenceID (RefCode.Value)
end sub
UPDATE! There's an error on this line (Run-time error 3464, "Data type mismatch in criteria expression"):
Set rec = CurrentDb.OpenRecordset(sSQL)
...in this code:
Private Sub RefCode_Change()
Dim rec As Recordset, RefID As Integer
sSQL = "select RefID from Exceptions where RefCode = '" & RefCode.Value & "'"
Set rec = CurrentDb.OpenRecordset(sSQL)
If (rec.EOF And rec.BOF) Then
RefID = 1
Else
rec.MoveFirst
RefID = rec.RecordCount + 1
End If
End Sub
I think you want to do this...
If (rec.EOF And rec.BOF) Then
'empty recordset
RefID = 1
Else
'at least one row
rec.movefirst
RefID = rec.RecordCount + 1
End If
You could also simplify all of that to
RefID = Dcount("*","Exceptions","refCode='" & RefCode & "'") +1
I'm not entirely sure what the problem is, but I see two potential issues:
you haven't specified your recordset declaration, so you could be running into the ambiguity between the DAO and ADO recordset types. Instead, declare your recordset variable as Dim rs As DAO.Recordset or Dim rs As ADOX.Recordset (I think that latter is correct -- I never use ADO, so never have to specify it!). The fact that Set rec = CurrentDb.OpenRecordset(sSQL) returns a data type mismatch strongly suggests to me that you have declared an ADO recordset, because that would cause a mismatch with the DAO recordset returned by CurrentDB.OpenRecordset().
DAO recordsets cannot be guaranteed to return an accurate Recordcount until you've traversed the entire recordset. Because of Jet/ACE's Rushmore technology, the beginning of the recordset is delivered while the end of it is still being retrieved. You could wait around for a while and hope the Recordcount is accurate, or you can explicitly make an rs.MoveLast, in which case the Recordcount will be guaranteed to be accurate.