Run SQL from VBA button - sql

What do I need to add/modify to this code to have txtDisease1 be populated with the results of strSQL? As of now the textbox populates with the SQL query. I'm sure it is a simple fix but for the life of me I can not find the answer.
Private Sub btnDNA_Click()
Dim strSQL As String
strSQL = "SELECT LastName From Patient WHERE PatientID = 1"
Me.txtDisease1.Value = strSQL
End Sub

You can use DLookup function.
Me.txtDisease1.Value = DLookup("LastName", "Patient", "PatientID = 1")

I've not been able to test this, but I think this should work.
Private Sub btnDNA_Click()
Dim strSQL As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
strSQL = "SELECT LastName From Patient WHERE PatientID = 1"
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)
Me.txtDisease1 = rs!LastName
rs.close
Set rs = Nothing
Set db = Nothing
End Sub

For more complex lookups or to hit other data sources, you can use ADO (requires reference to Microsoft Active X Data Objects)
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "SELECT TOP 1 LastName From Patient WHERE PatientID=1", _
CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
If Not rs.EOF Then Me.txtDisease1.Value = rs(0)
rs.Close
Set rs = Nothing

Related

recordset data is not populated in txt field

I am new to Access and VBA trying to explore. I have a form where there is two text boxes(txtAc & txtFirstName), I want data to be populated in txtFirstName on the basis of SQL query based on parameter of txtAc. I tried to achieve the same by recordset. Please review my code below: -
Private Sub txtCust_Click()
Dim cnn As ADODB.Connection
Dim strSQL As String
Dim rst As ADODB.Recordset
Set cnn = CurrentProject.Connection
Dim i As Integer
Dim Records As Integer
Dim AcN As Double
Dim AcNo As Double
AcN = Forms!dfrmAccount!txtAc.Value
AcN = AcNo
strSQL = "SELECT dtblCustomer.[FIRST_N], dtblAccount.[ACCOUNT_NO] FROM
dtblAccount INNER JOIN dtblCustomer ON dtblAccount.[CUSTOMER_ID] =
dtblCustomer.[CUSTOMER_ID] WHERE (((dtblAccount.[ACCOUNT_NO])='AcNo'))"
Set rst = New ADODB.Recordset
rst.CursorLocation = adUseClient
rst.Open strSQL, cnn
Records = rst.RecordCount
Debug.Print rst.RecordCount
For i = 1 To Records
Me.txtFirstName.Value = rst.Fields!FIRST_N
Debug.Print rst.Fields!FIRST_N
rst.MoveNext
Next i
'' Clean up
rst.CLOSE
Set rst = Nothing
End Sub
Thanks in advance. Plz somebody help.
...(((dtblAccount.[ACCOUNT_NO])='AcNo'))"
should be
...(((dtblAccount.[ACCOUNT_NO])=" & AcNo & "))"
assuming ACCOUNT_NO is a numeric field.
You're also not populating AcNo - it will have the default value of zero.

Error while storing records from Access field in array

Situation :
I have this code which stores all the records from the field Shipment ID in an array called arrayShipmentID.
Dim conn As New ADODB.Connection
Dim connStr As String
Dim rs As ADODB.Recordset
Dim ShipmentIDSQL As String
Dim arrayShipmentID() As Variant
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "P:\PathToTheAccessDatabase\" & "NewVersion.accdb" & ";"
conn.ConnectionString = connStr
conn.Open
' Store Shipment IDs
Set rs = New ADODB.Recordset
ShipmentIDSQL = "SELECT [Shipment ID] FROM 12Dec"
rs.Open ShipmentIDSQL, conn, adOpenStatic, adLockReadOnly, adCmdText
If Not rs.EOF Then
arrayShipmentID = rs.GetRows
End If
Dim i As Integer
For i = 0 To UBound(arrayShipmentID, 2)
Debug.Print arrayShipmentID(0, i)
Next i
Set rs = Nothing
In order to make sure it works I Debug.Print each element of the array.
Issue :
This code WORKS most of the time, but for some reason, sometimes I get as a value 'subscript out of range' (instead of 181 in my case) for MsgBox UBound(arrayShipmentID, 2) and of course in that case Debug.Print doesn't display anything in the Immediate Window.
Any ideas where could this come from ?
With DAO recordsets you often have to find the recordcount to retrieve all records. That might be the case for ADO as well:
RecordCount = ' Obtain true count of records.
arrayShipmentID = rs.GetRows(RecordCount)
Also, I normally declare the variable as a simple Variant:
Dim arrayShipmentID As Variant

How to execute an SQL statement in VBA using " sign to Get the ID with RecordSet Access 2013

I am looking to execute the following code, the problem is, I need to put a String variable in the SQL which should use the "" sign inside the SQL statement.
The problem is, I cannot use multiple "". I tried using Char to use the sign " and convert it to a String, and that's when I got lost.
The code below shows 2 Functions. 1 To see if I get it right to print the correct SQL statement, the other is a Function to return the actual record ID which I will then use to add a new record.
What I mainly looking to do, is use the RecordSet to get a record ID of one of the records.
Any help would be highly appreciated.
Private Sub PrintSQLStatement_Click()
Dim strSQL As String
Dim strTmp As String
Dim i As Integer
strTmp = "UE243"
strSQL = "SELECT tbl_Sales.[ID], tbl_Sales.[SaleReference] FROM tbl_Sales WHERE (((tbl_Sales.[SaleReference])= "" + strTmp + ""));"
i = MsgBox(strSQL, vbOKOnly)
End Sub
Private Function GetSaleID(ByVal strSaleRef As String) As Integer
Dim db As Database
Dim rs As Recordset
Dim strSQL As String
Dim ID As Integer
strSQL = "SELECT tbl_Sales.[ID], tbl_Sales.[SaleReference] FROM tbl_Sales WHERE (((tbl_Sales.[SaleReference])= "" + strSaleRef + ""));"
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)
ID = rs.GetID
rs.Close
Set rs = Nothing
db.Close
GetSaleID = ID
End Function
You can avoid character escaping issues by using a QueryDef object to run a parameterized query like so:
Private Function GetSaleID(ByVal strSaleRef As String) As Long
Dim db As DAO.Database
Dim qd As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strSQL As String
Dim ID As Long
strSQL = _
"PARAMETERS prmSaleRef TEXT(255);" & _
"SELECT tbl_Sales.[ID] FROM tbl_Sales " & _
"WHERE tbl_Sales.[SaleReference]=[prmSaleRef]"
Set db = CurrentDb
Set qd = db.CreateQueryDef("", strSQL)
qd!prmSaleRef = strSaleRef
Set rs = qd.OpenRecordset(dbOpenSnapshot)
ID = rs!ID
rs.Close
Set rs = Nothing
Set qd = Nothing
db.Close
Set db = Nothing
GetSaleID = ID
End Function

Use SQL Statement in access 2007 [duplicate]

What's wrong with this code:
Visual Basic 6.0 With access 2007
Private Sub Command1_Click()
Dim Sell_tbl, Stock_Bottle, res As String
Sell_tbl = "SELECT Sum((Quantity)*12) FROM Sell_Detail Where Cateogry='Large'"
Stock_Bottle = "Select Sum(No_Of_Bottle) FROM Add_Bottle Where Cateogry='Large'"
res = ((Sell_tbl) - (Stock_Bottle))
Adodc1.RecordSource = Sell_tbl
Adodc1.Refresh
Adodc1.Caption = Adodc1.RecordSource
End Sub
Type Mismatch Error
I try to convert its result in other data type but it doesn't work. Can anyone help me?
Neither of these is a recordset, each is a string:
Sell_tbl = "SELECT Sum((Quantity)*12) FROM Sell_Detail Where Cateogry='Large'"
Stock_Bottle = "Select Sum(No_Of_Bottle) FROM Add_Bottle Where Cateogry='Large'"
You need something on the lines of:
Dim Sell_tbl As DAO.Recordset
Dim Stock_Bottle As DAO.Recordset
Set Sell_tbl = CurrentDB.Openrecordset _
("SELECT Sum((Quantity)*12) As Qty FROM Sell_Detail Where Cateogry='Large'")
Set Stock_Bottle = CurrentDB.Openrecordset _
("Select Sum(No_Of_Bottle) As Btl FROM Add_Bottle Where Cateogry='Large'")
res = Sell_tbl!Qty - Stock_Bottle!Btl
The above is a rough outline, it could do with tidying up.
The reason for the error is because of statement:
s = ((Sell_tbl) - (Stock_Bottle))
If you look above that line, you are setting two string variables to SQL -- which is text not numeric.
You need to open recordsets with those sql strings, then get the results, then perform the math.
It is what I want....
Private Sub Command2_Click()
Dim con As New ADODB.Connection
con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
& App.Path & "\add_entry.mdb;Persist Security Info=False"
Dim rs As New ADODB.Recordset
Dim rs1 As New ADODB.Recordset
Dim result_hold As Integer
Dim large_tbl As String
Dim sell_large As String
large_tbl = "SELECT Sum(No_Of_Bottle) FROM add_cotton where Cateogry='Large'"
sell_large = "SELECT Sum(Quantity) FROM Sell_Detail where Cateogry='Large'"
rs.Open large_tbl, con, adOpenDynamic, adLockOptimistic
rs1.Open sell_large, con, adOpenDynamic, adLockOptimistic
result_hold = CInt(rs.Fields(0).Value) - CInt(rs1.Fields(0).Value)
Text1.Text = CStr(result_hold)
End Sub
'if u need to retreive whole colum use loop or etc.. but one thing is remember to you two sources
'never attach with single grid...

The Microsoft Jet database engine could not find the object "SELECT * FROM funk"

I want to write a very simple query and bind it to a listbox with VBA code but an error occures by running this piece of code:
Private Sub Command0_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM funk", dbOpenTable)
Me.List9.Recordset = rs
End Sub
the name of the databse is correct. Could you please inform me how can I solve this problem?
Edit
I've changed my code to
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM funk")
Me.List9.Recordset = rs
but it doesn't work too
There is no need for such complication:
Private Sub Command0_Click()
Me.List9.Rowsource = "SELECT * FROM TableName"
End Sub
However, it would be much better to say:
Me.List9.Rowsource = "SELECT ID,VisibleField FROM TableName"
You can the hide the ID field yet any selection in a simple select is equal to the ID when the Bound Column is 1.
You will need:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
'dbOpenDynaset is the default here, but it would not be the default for
'a local table
Set rs = db.OpenRecordset("SELECT * FROM funk",dbOpenDynaset)
Set Me.List9.Recordset = rs
Note Set on the last line.