VBA access run sql check row count - sql

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

Related

(Access VBA touchup) Auto Populating after update based on another textbox

Hello I'm trying my best to piece together a code to have all text boxes on the form update to existing records.
All the textboxes are updating beside
Me.txtSftLvl = myrs!SafteyStockLvl
I am left with the error
Item Cannot Be Found In The Collection (3265)
I have double checked my naming on the table and textbox itself and they are fine...
Hoping someone would know what im doing wrong or a simpler way of accomplishing my goals.
Private Sub txtRcStock_AfterUpdate()
Dim qrystr1 As String
Dim mydb As Database
Dim myrs As DAO.Recordset
DoCmd.OpenQuery "qryPartDesc"
If Me.txtRcStock <> "" Then
Set mydb = CurrentDb
qrystr1 = "SELECT Desc FROM qryPartDesc WHERE [PartNumber] = '" & Me.txtRcStock & "'"
Set myrs = mydb.OpenRecordset(qrystr1)
If myrs.EOF = False Then
Me.txtRcCat = myrs!Desc
End If
qrystr1 = "SELECT Price FROM tblRecLog WHERE [PartNumber] = '" & Me.txtRcStock & "'"
Set myrs = mydb.OpenRecordset(qrystr1)
If myrs.EOF = False Then
Me.txtPrice = myrs!Price
If myrs.EOF = False Then
Me.txtSftLvl = myrs!SafteyStockLvl
End If
End Sub
Anything helps.

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

How to assign the value to the Access column in the where clause?

In My project, we connecting to MS Access from MS Excel, in excel we have one dropdown (medd) with Yes or No values. At the same time, in MS Access, we have column Med_D with Y or N values.
So, if the user selects 'Yes' from the dropdown, then it should fetch the MS Access rows where Med_D = Y.
If the user selects 'No' from the dropdown, then it should fetch the MS Access rows where Med_D in ('Y','N').
I want to check this condition in a single query, we cant use CASE in Access, tried IIF & Switch but I got failed.
use this:
Select * from "Table Name" Where Med_D = "xxxxx"
xxxxx is the dropdown with Y and N
Im guessing your using ADODB connection?
here's a more detailed view of the code:
Sub Extract()
Blah = yourdropdown.value
Set Con1 = New ADODB.Connection
Set RcdSet1 = New ADODB.Recordset
Application.ScreenUpdating = False
DBPath = "" <<<path of your access database
DBProvider = "Provider=Microsoft.Jet.OLEDB.4.0;"
DBParam = DBProvider & "data source =" & DBPath
Con1.Open DBParam
RcdSet1.ActiveConnection = Con1
RcdSet1.Open "Select * from "Table Name" Where Med_D = "Blah""
rcdset1.movefirst
Range("xx").copyfromrecordset rcdset1 <<< where you will paste the records to
rcdset1.close
set rcdset1 = Nothing
end sub
have fun =)
Sub MakeDynamicSQL()
Const SQL As String = "select * from YourAccessTable"
Dim sWhereClause As String
Select Case Cells(1, 1).Text ' cell A1 contains Y or N
Case "Y": sWhereClause = " where Med_D = 'Y'"
Case "N": sWhereClause = " where Med_D in ('Y','N')"
Case Else: MsgBox "error": Exit Sub
End Select
Debug.Print SQL & sWhereClause ' send this to Access
End Sub

Access VBA Recordset

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?

Populate field in ms access form from field in ado recordset record of the same name

I have a form in Access that I am trying to populate during it's Current event using the fields from an ADO Recordset. I am using Sql Server for the database and am using the recordset to try to populate to corresponding fields on the form with what is in the recordset. Right now it works like this:
Private Sub Form_Open(Cancel As Integer)
On Error GoTo Err_FormOpen
Set rst As new ADODB.Recordset
With rst
.ActiveConnection = CurrentProject.AccessConnection
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Source = "SELECT * FROM [Outage Summary] ORDER BY OutageSummaryID"
.Open
End With
Set Me.Recordset = rst
End Sub
Private Sub Form_Current()
OutageSummaryID.Value = Me.Recordset!OutageSummaryID
Dispatcher.Value = Me.Recordset!Dispatcher
StartDateTime.Value = Me.Recordset!StartDateTime
Location.Value = Me.Recordset!Location
CityRelated.Value = Me.Recordset!CityRelated
Scheduled.Value = Me.Recordset!Scheduled
CustomerEquip.Value = Me.Recordset!CustomerEquip
DispatchBusHrs.Value = Me.Recordset!DispatchBusHrs
TotalCount.Value = Me.Recordset!TotalCount
Substation.Value = Me.Recordset!Substation
CompletionDateTime.Value = Me.Recordset!CompletionDateTime
CustCallDateTime.Value = Me.Recordset!CustCallDateTime
FirstRespDateTime.Value = Me.Recordset!FirstRespDateTime
Feeder.Value = Me.Recordset!Feeder
SwitchingSchedule.Value = Me.Recordset!SwitchingSchedule
Cause.Value = Me.Recordset!Cause
ActionTaken.Value = Me.Recordset!ActionTaken
Me.ME.Value = Me.Recordset!ME
MI.Value = Me.Recordset!MI
End Sub
But I would like the current subroutine to work something like this:
Dim fld As ADODB.Field
Dim nam As String
For Each fld In Me.Recordset.Fields
Debug.Print fld
nam = fld.Name
Me.Controls(nam).Value = fld.Value
Next
With the code as it stands I am getting an error "The recordset is not updatable"
Thanks for any help!
This is because you are not binding to the recordset. It would be better if you stored your query and attached it to the form as the recordsource so that way it will bind it to the form. Then you set the record source of each field in design mode and no code is needed and it will be updateable depending on your permission to the SQL Server.