I am vba code beginner. I am writing a vba code to extract data from mysql database. I have made successful connection with mysql server. Basically, database has 4 fields such as id, id_id, descr and notation.
I am trying to populate the combobox in userform by field list. Let say, I want to populate the descr list based on id_id field. I tried to create recordset as below
sqlQa = "select descr from matcat_select order by descr & id_id = int;"
FYI, id_id might be int or string.
See the code for data extraction from database and populate into Combobox
sqlQa = "select descr from matcat_select"
Where id_id = 20
Order by descr;"
'sqlQa = "select descr from matcat_select where id_id = 20;"
rs.Open sqlQa, oConn, adOpenStatic
With rs
'Set .ActiveConnection = Nothing 'Disconnect the recordset
.k = .Fields.Count
'Populate the array with the whole recordset
.vaData = .GetRows
End With
'Close the connection.
oConn.Close
'Manipulate the Combobox's properties and show the form.
With UserForm1
With .ComboBox1
.Clear
.BoundColumn = k
.List = Application.Transpose(vaData)
.ListIndex = -1
.ColumnCount = 2
End With
'.Show vbModal
End With
Please help me to solve this issues.
If you are not sure if the id_id field is an int then input it as a string by surrounding it by single quotes.
Use where clause to fetch records for matching id_id value.
Change:
sqlQa = "select descr from matcat_select
order by descr & id_id = int;"
To:
sqlQa = "select descr from matcat_select
where id_id = 'value_of_id_id_here'
order by descr;"
Related
I will explain this as much as possible.
I have a project which need to show the names from database to textboxes. I have 2 datetimepicker for searching between dates and 5 textboxes to show the names in mysql database. for example I select the from start date 2018/12/07 and end date 2019/01/07 in the datagridview it will show all the rows and columns in-between dates. However, I need the names to show on my 5 textboxes. I don't have a code since I don't know where to begin with.
In mysqldatabase I have only id,name,dateofentry.
In my form :
datetimepicker1 = startdate
datetimepicker2 = enddate
button1 = generatebutton
textbox1 = nametxt1
textbox2 = nametxt2
textbox3 = nametxt3
textbox4 = nametxt4
textbox5 = nametxt5
Update when I use this:
mysqlconn.Open()
COMMAND.Connection = mysqlconn
COMMAND.CommandText = "Select name from table1 where dateofentry between '" & Format(Me.startdate.Value, "yyyy-MM-dd") & "' AND '" & Format(Me.endtime.Value, "yyyy-MM-dd") & "'"
Dim sqlresult1 As Object
sqlresult1 = COMMAND.ExecuteScalar
Dim str1 As String
str1 = sqlresult1
nametxt1.Text = str1
mysqlconn.Close()
The same name shows in each of my 5 textboxes
Thank you for answering this question.
Explanations and comments in-line.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'The Using block ensures that your database objects are closed and disposed
'even if there is an error
Dim dt As New DataTable
Using cn As New MySqlConnection("Your connection string")
'Pass the Select statement and the connection to the constructor of the command
Using cmd As New MySqlCommand("Select name from table1 where dateofentry between #Date1 AND #Date2;", cn)
'Use parameters
cmd.Parameters.Add("#Date1", MySqlDbType.Date).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Date2", MySqlDbType.Date).Value = DateTimePicker2.Value
'open the connection at the last possible moment
cn.Open()
'Execute scalar only returns the first row, first column of the result set
dt.Load(cmd.ExecuteReader)
End Using
End Using
'Then a little link magic to dump the first column of the table
'to an array
Dim names() = (From row In dt.AsEnumerable()
Select row(0)).ToArray
'If there are less than 5 records returned this
'code will fail, Add a check for this and
'adjest your code accordingly
TextBox1.Text = names(0).ToString
TextBox2.Text = names(1).ToString
TextBox3.Text = names(2).ToString
TextBox4.Text = names(3).ToString
TextBox5.Text = names(4).ToString
End Sub
SELECT *
FROM `tblPerson`
WHERE (date_field BETWEEN '2018-12-30 14:15:55' AND '2019-01-06 10:15:55')
LIMIT 5;
text1.text = dt.Rows[0]["name"].ToString();
text2.text = dt.Rows[1]["name"].ToString();
text3.text = dt.Rows[2]["name"].ToString();
text4.text = dt.Rows[3]["name"].ToString();
text5.text = dt.Rows[4]["name"].ToString();
I have a SQL VBA query for updating values in several textboxes on a form on the click of a button.
The query takes the input from the multiple label name captions on the form. So caption of Label1 will be input for TextBox1, Label2 caption for Textbox2 etc.
I am trying to pass the label name through a variable to the query. However the following error is returned on the line where value of variable b is generated:
"Microsoft Access can't find the field '&labelname&'referred to in your expression.
My code is below. I want to use a variable so that later I can make it a function to accept the label name and return the recordset value. In this way I will be able to avoid approx. 150 lines of code as I have to update 20 to 25 textboxes with the input from same number of labels.
Private Sub Command111_Click()
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Dim ssql As String
Dim labelname As String
Dim b As String
Set dbs = CurrentDb
'--------------------------------------------------------------------------- ----
labelname = "Label24"
b = [Forms]![Bal_Sheet]![& labelname &].Caption
ssql = "select sum(a.[Bal Fwd]) from Trial_Balance a,Act_Master b where a.GBOBJ = b.object and a.GBSUB = b.sub and b.Cat = " & "'" & b & "'"
Debug.Print ssql
Set rs = dbs.OpenRecordset(ssql, dbOpenDynaset)
[Forms]![Bal_Sheet]![Text1].Value = rs(0)
'-------------------------------------------------------------------------------
rs.Close
Set rs = Nothing
dbs.Close
End Sub
Your expression:
b = [Forms]![Bal_Sheet]![& labelname &].Caption
Is not concatenating a string, as [Forms] and [Bal_Sheet] refer to objects.
Instead, you should use:
b = Forms("Bal_Sheet").Controls(labelname).Caption
I'm trying to change the recordset of a subform to display the query result
So I have a string query :
sQueryCurrencyRate = "SELECT * FROM Table.Mytable WHERE As_Of_Date =" & Format(dateField.value, "M/d/yyyy")
sQueryCurrencyUsDollar = "SELECT * FROM Table.Mytable WHERE As_Of_Date =" & Format(dateField.value, "M/d/yyyy")
So when I write this , the subform display a result without error :
Me.subformName.Form.RecordsourceSourceObject = "Table.tableName"
but When I try all of the below I always receive an error :
Forms!formName.subformName.Form.RecordSource= sQueryCurrencyRate
I have also tried :
Me.subFormName.Form.RecordsourceSourceObject= sQueryCurrencyRate
Also ,
Me.subFormName.RecordsourceSourceObject= sQueryCurrencyRate
No matter what I do , I always end up having this error message :
the expression you have entered refers to an object that is closed or
doesn't exist
What I'm doing wrong? and how to properly display the query result in the subform recordsource ?
P.S: the sql queries syntax are fine because I have previously tested them with :
Set db = CurrentDb
Set rs = db.OpenRecordset(sQueryCurrencyRate)
and I received no error , so the problem is how to bind the subform result to the query
EDIT:
The way I'm calling the code is like below :
Function detectSelectedQuery(sTypeDonnee As String)
sQueryCurrencyRate = "SELECT * FROM Table.Mytable WHERE As_Of_Date = ' " & Format(dateField.value, "M/d/yyyy") &"'"
Me![Child8].Form.RecordSource = sQueryCurrencyRate
end function
then when the combobox is changed I call the function :
Private Sub Combo_descriptionQueries_Change()
detectSelectedQuery (Combo_descriptionQueries.Value)
End Sub
If you want to do this properly (without any risk of SQL injection), you can use an ADODB recordset:
Dim cmd As New ADODB.Command
cmd.CommandText = "SELECT * FROM Mytable WHERE As_Of_Date = #MyDate"
cmd.ActiveConnection = CurrentProject.Connection
cmd.ActiveConnection.CursorLocation = adUseClient
cmd.Parameters("#MyDate") = cmd.CreateParameter("MyDate", adDate)
cmd.Parameters("#MyDate").Value = datefield.Value
Set Me.Recordset = cmd.Execute
Note that this requires a reference to the ActiveX Data Objects library
Use this:
sQueryCurrencyRate = "SELECT * FROM Mytable WHERE As_Of_Date = #" & Format(dateField.value, "yyyy\/mm\/dd") & "#"
To avoid concatenating, you could use TempVars or create a small helper function:
' Public variable:
Dim FilterDate As Date
Public Function GetFilterDate() As Date
GetFilterDate = FilterDate
End Function
and then an extra line of code:
FilterDate = Me!dateField.Value
sQueryCurrencyRate = "SELECT * FROM Mytable WHERE As_Of_Date = GetFilterDate()"
Since this is in Access, why not use the default DAO interface with a parameter query instead of ADODB? No need for an ActiveX Data Objects reference.
Dim qdf As DAO.QueryDef
'For an existing query
Set qdf = CurrentDb().QueryDefs("qryName")
'To create query (Credit to #Erik von Asmuth for pointing this out)
Set qdf = CurrentDb().CreateQueryDef("", "PARAMETERS [#MyDate] DateTime; SELECT * FROM Mytable WHERE As_Of_Date = [#MyDate];")
qdf.Parameters("[#MyDate]").Value = Date()
Set Me.Recordset = qdf.OpenRecordset()
I have VBA code that queries a table. The Query view in MS Access returns the correct results, however the vba returns a different result.
Table called tbl_ADMIN_CLASS_INFO
Client_ID | POLICY_GROUP
12345a | 1
12345a | 2
12345a | 2
12345a | 2
12345a | 2
Column Definitions from Table:
CLIENT_ID = Text
POLICY_GROUP = Number
VBA
Public Sub NextPageControl()
Dim dbs As Database
Dim rst As Recordset
Dim CurrentTableName As String
Dim CurrentFormName As String
Dim NextPageSQL As String
Dim CurrentPage As Form
Dim LastRecord As Integer
Dim Nextpage As Integer
Dim TestPolicy As Long
Dim TestClient As String
TestPolicy = Forms!frm_ADMIN_CLASS_INFO.POLICY_GROUP 'Stepping Through Code shows 12345a
TestClient = Forms!frm_ADMIN_CLASS_INFO.CLIENT_ID 'Stepping Through Code shows 2
CurrentTableName = Screen.ActiveForm.RecordSource
CurrentFormName = Screen.ActiveForm.Name
Set CurrentPage = Screen.ActiveForm
Set dbs = CurrentDb
NextPageSQL = "SELECT * FROM " & CurrentTableName & " WHERE ((POLICY_GROUP = " & TestPolicy & ") AND (CLIENT_ID = '" & TestClient & "'))"
Debug.Print NextPageSQL
Set rst = CurrentDb.OpenRecordset(NextPageSQL, dbOpenDynaset)
MsgBox rst.RecordCount
...More Stuff
The problem is that this VBA returns 5 for rst.RecordCount when it should return 4....
Firstly, the following instruction is not optimal as it can fool you if you're in the case where your form's record source is a SQL query and not a table:
CurrentTableName = Screen.ActiveForm.RecordSource
So make sure that this instruction retruns the correct table name.
Secondly: using recordset.recordcount might not return the expected results depending on your cursor type and the datasource. From microsoft:
The cursor type of the Recordset object affects whether the number of
records can be determined. The RecordCount property will return -1 for
a forward-only cursor; the actual count for a static or keyset cursor;
and either -1 or the actual count for a dynamic cursor, depending on
the data source.
So to be sure you're always returning the correct amount of records, do a :
rst.movelast
prior to do the recordcount
Your code should work fine after those corrections.
I'm learning SQL Server and VB.NET. My problem is how to select and make a condition to specific row in the table.
Like, that I have table with two columns name, age, and I want to select rows where name is "XY".
After that, make a condition with an (if) statement like: if age (in the table) larger than 20.
Do some thing or each one his name "xy" print his age in a messagebox.
You can try this in one query like this:
select * from yourtable where name = 'XY' and age > 20
Noor, Rahul was exactly correct in what was recommended. It sounds like you have little experience with how to get data from a SQL query into a useable form so you can test and manipulate or analyze data. For technology, look at ADO, and ADOX usage in VB.NET with SQL queries. My recommendation is for you to purchase one or more good books on VB.NET, so you can fully understand how to move forward.
Dim filename As String = "C:\myfile.mdb"
Dim tablename as String = "mytable"
Dim ConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data source =" & filename
Dim cn As New OleDbConnection(ConnString)
cn.Open()
Dim qry As String
Dim cmd As New OleDbCommand(qry, cn)
qry = "SELECT * FROM [" & tablename & "] WHERE name = "XY" and age > 20 ORDER by age "
cmd.CommandText = qry
cmd.Connection = cn
Dim drdata As OleDbDataReader = cmd.ExecuteReader
Dim Cnt As Integer = 0
Dim name(), age() as Object
Do While drdata.Read
Cnt += 1
Redim Preserve name(Cnt)
Redim Preserve age(Cnt)
name(Cnt) = drdata.Item("name")
age(Cnt) = drdata.Item("age")
Loop
drdata.Close()
For i As Integer = 1 to Cnt
If age(i) = 20 Then
' do anything you want here
End If
Next i