ms access database search does not work as intended - ms-access

The table name is water and it has two field fname and serial.
In the field fname suppose a value 'bill' has 3 serial 1, 2, and 3. now I need when I type bill in textbox1 and click search button, the combobox1 should show the serials of 'bill' are 1,2 and 3.
I'm using ms access as db and I'm using this code but it not working.
Is there any other way to solve this?
Set rs4 = cn.Execute("select fname, serial from water where fname = '" & Text1.Text & "'")
rs4.MoveFirst
Do While Not rs4.EOF
Combo1.AddItem rs4("serial")
rs4.MoveNext
Loop

You could have a problem when someone enters a single-quote in to the text box. You should do something like this:
Set rs4 = cn.Execute("select fname, serial from water where fname = '" & Replace(Text1.Text, "'", "''") & "'")
Another problem you may have is if there is no match found. You're not checking to see if there is any data in the recordset object.
Combo1.Clear
Set rs4 = cn.Execute("select fname, serial from water where fname = '" & Replace(Text1.Text, "'", "''") & "'")
If not rs4.Eof Then
rs4.MoveFirst
Do While Not rs4.EOF
Combo1.AddItem rs4("serial")
rs4.MoveNext
Loop
End If

I'm not really sure what the problem is, but your loop should look something more like this:
rs4.MoveFirst
Do While Not rs4.EOF
Combo1.AddItem rs4("holding")
rs4.MoveNext
Loop

Have you considered telling the compiler more explicitly what you want, something more like:
Set rs4 = cn.Execute("select fname, serial from water where fname = '" & Text1.Text & "'")
With rs4
Do Until .EOF
Combo1.AddItem CStr(!serial.Value)
.MoveNext
Loop
End With

Related

Insert checked list box to database

I have 6 checked boxes with more than 10 values each in my Visual Basic project using Visual Studio.
I would like to insert the values of the checked box into one table, all values of checked box into one cell (if possible).
For example, I have table called Food that has user id, Fruits, Vegetables, and Snacks.
Assuming that I have 3 checked boxes as well, I want to have all Fruits checked in Fruit column as it represents one person.
I started my code like this:
sql = "INSERT INTO Food (id, Fruits, Vegetables, Snacks) VALUES ('" & txtIDR.Text & "','" & CheckedFruits.CheckedItems.ToString & "','" & CheckedVegetables.CheckedItems.ToString & "','" & CheckedSnacks.CheckedItems.ToString & "','" & ")"
I didn't got an error messages but I'm afraid that I did something wrong with the way I handled the checked list box.
Please advise.
Edit: Sorry didn't see it was CheckListBox
to access a property of the CheckListBox you should use:
CheckedListBox1.CheckedItems.Item(0)
Where 0 is your item index
However you need to remember that CheckedItems.Item will only exist if something is checked if you try to call CheckedListBox1.CheckedItems.Item(0) but nothing is checked you will get Index out of bounds
An easy way to get all checked values easily is with a For Each:
For Each check In CheckedListBox1.CheckedItems
Debug.WriteLine(check)
Next
You could have something like this:
Public Function CreateSQL() As SqlCommand
Dim Fruits As String = ""
Dim Vegetables As String = ""
Dim Snacks As String = ""
For Each check In CheckedFruits.CheckedItems
Fruits = Fruits & check & ","
Next
If Fruits.LastIndexOf(",") = Fruits.Length - 1 Then
Fruits = Fruits.Remove(Fruits.LastIndexOf(","), 1)
End If
For Each check In CheckedVegetables.CheckedItems
Vegetables = Vegetables & check & ","
Next
If Vegetables.LastIndexOf(",") = Vegetables.Length - 1 Then
Vegetables = Vegetables.Remove(Vegetables.LastIndexOf(","), 1)
End If
For Each check In CheckedSnacks.CheckedItems
Snacks = Snacks & check & ","
Next
If Snacks.LastIndexOf(",") = Snacks.Length - 1 Then
Snacks = Snacks.Remove(Snacks.LastIndexOf(","), 1)
End If
MyCommand = New SqlCommand("INSERT INTO Food (id, Fruits, Vegetables, Snacks) VALUES (#UserID, #Fruits, #Vegetables, #Snacks)", dbConn)
MyCommand.Parameters.AddWithValue("#UserID", TicBoxText.Text)
MyCommand.Parameters.AddWithValue("#Fruits", Fruits)
MyCommand.Parameters.AddWithValue("#Vegetables", Vegetables)
MyCommand.Parameters.AddWithValue("#Snacks", Snacks)
Return MyCommand
End Sub
CheckedListBox MSDN

Run-time error '13' Type Mismatch MS Access VBA array

Have been trying to insert a Street, Suburb and a postcode into a table but keep getting
Run-time error '13'
Type mismatch
Here is the code:
Sub arrayData()
Dim CustomerNames() As Variant
Dim num As Long, dbs As Database, InsertReocrd As String
Dim CustomerID As Long, num1 As Long
Dim CustomerName As String
Dim Street As String, Suburb As String, Postcode As Integer
Set dbs = CurrentDb()
CustomerID = 0
For num1 = 0 To 50000
CustomerID = CustomerID + 1
CustomerNames = Array(...)
Street = Array("Short", "Lygon", "Flinders", "Elizabeth", "King") //ERROR OCURRS HERE
Suburb = Array("Sandringham", "Brighton", "St Kilda", "Melbourne", "Carlton") //ERROR OCURRS HERE
Postcode = Array("3165", "3298", "3145", "3144", "3000") //ERROR OCURRS HERE
num = Int((250 - 0 + 1) * Rnd + 0)
CustomerName = CustomerNames(num)
InsertRecord = "INSERT INTO CUSTOMER (CustomerID , CustomerName, StreetName, Suburb) VALUES (" & "'" & CustomerID & "'" & "," _
& "'" & CustomerName & "'" & "'" & StreetName & "'" & ")"
dbs.Execute InsertRecord
Debug.Print CustomerID, CustomerName, Street, Suburb
Next
End Sub
Variables that should hold arrays need to be declared as Variant, not as String.
So:
Dim Street As Variant, Suburb As Variant, Postcode As Variant
Note that your INSERT statement is missing the value for Suburb.
Using DAO.Recordset.AddNew etc. would probably be faster and better readable.
As shown yesterday, simplify your concatenation, and you also need and array for the CustomerID and a loop as well:
For n = 1 To 5
InsertRecord = "INSERT INTO CUSTOMER (CustomerID , CustomerName, StreetName, Suburb) VALUES (" & CustomerID(n) & ",'" & CustomerName(n) & "','" & StreetName(n) & "','" & Suburb(n) & "')"
If you really wish to insert 50000 customers this way(?) (you wouldn't), follow the advice from André and use DAO.
Sorry if this doesn't exactly fit the topic. Just in case any other poor fool spends hours trying to figure out why they're getting a 'Type Mismatch' on a VBA recordset.addnew, check the [Default Values] of the fields/columns in the table. I changed a TEXT field to a DATE field, but neglected to remove the "" in [Default Value]. (trying to set any text value to a date field is a no-no).

Not able to read from access table properly

I have encountering a very silly problem. The requirement is to stop the duplicate entry in access table. I am using Vb6. But each time I try I am encountering syntax error.
My code
My flexgrid is populated and refreshed. I am able to insert and select data in another table in same database. But this one is failing
sql_txt1 = "Select SL_No from SpAIReport where DOM ='" & Format(Now, "mm/dd/yyyy") & _
"' and AC-REG ='" & msgDisFlex.TextMatrix(i, 4) & "' and Flt No = '" & msgDisFlex.TextMatrix(i, 6) & "'"
Set rs1 = db.OpenRecordset(sql_txt1)
I am able to update this table, but multiple time same data are getting populated.
The access table structure with the entries are given below
Date_OF_Fly Flt No GMT Weight Airtime Station DOM Data_hrs Filename
7/3/2000 11 03:45:01 5 01:23:40 XXX 01/25/2014 120:10:15 ABCD
Plus, after saving if I want to access it through recordset then it is showing NULL.
The code is:
sql_txt = "select * from SpAIReport where DOM='" & dateDailyReport & "'"
Set rs = db.OpenRecordset(sql_txt)
The dateDailyReport value is 01/25/2014. This value is present in database. Still this query is not working.
Please help.
You probably want to put 'Flt No' and 'AC-REG' in square brackets otherwise they look like two field names:
"' and [AC-REG] ='" & msgDisFlex.TextMatrix(i, 4) & "' and [Flt No] = '" &

Access 2010 - Check data in recordset before adding new record

I'm new to Access so bear with me here.
I have a form that allows me to add new data to a table
ID | Name | City | Zip Code
1 | John | Newark | 12340
2 | Alex | Boston | 98760
So on and so forth...
Before proceeding to add a new record with the above data fields, I need to create a check that will look at the table to determine if the combinations of Name, City and Zip Code already exist. If they do, I want it to Exit Sub; Else continue with the rest of the macro.
I've been looking to build this using some form of the OpenRecordset command, but I'm not sure where to begin. Can someone point me in the right direction? Thanks!
I just wrote this code to recreate your situation and it worked fine. You just need to rename your columns and your table in the query.
Dim strSQL As String
Dim qdf As QueryDef
'if these columns are not text change to approriate type
strSQL = "PARAMETERS [NameToCheck] Text(255),[CityToCheck] Text(255),[Zip] Text(255); "
'change table name and column names here
strSQL = strSQL & "SELECT Count(*) FROM address " _
& "WHERE FName = [NameToCheck] AND City = [CityToCheck] AND ZipCode = [Zip];"
Set qdf = CurrentDb.CreateQueryDef("", strSQL)
qdf("NameToCheck") = txtName.Value 'change to that textfield on form
qdf("CityToCheck") = txtCity.Value 'change to that textfield on form
qdf("Zip") = txtZipCode.Value 'change to that textfield on form
If qdf.OpenRecordset(dbOpenSnapshot)(0) > 0 Then
MsgBox "This record is already in the database"
Else
'Insert statement goes here.
End If
If you want to use recordsets as you requested then you would need to use a SQL statement to select all or use it to find something by name.
Dim myR as Recordset
Dim strSQL as String
'run a SQL statement to select a record with the same info
strSQL = "SELECT [Name], [City], [Zip Code] FROM table_name_here " & _
"WHERE [Name] = '" & form_control_name & "' " & _
"AND [City] = '" & form_control_city & "' " & _
"AND [Zip Code] = '" & form_control_zip & "'"
'set your recordset to the SQL statment
Set myR = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset)
'if your count is greater than 0, then you'll have a duplicate
If myR.RecordCount > 0 then
MsgBox "This already exists"
Else
MsgBox "All clear"
End if
Set myR = Nothing

MS Access query to separate commas

my project contains a MS Acces 2003 database, The table in the database contains a column called students name. The single column contains n numbers of names of student. For eg. John, Jim, Johny, Tom etc. They are dynamically added. Now what I want is, I want a complete list of all the names in the column.
Like for eg. if the column is
Student_name
John, Jim, Johny, Tom, Jack
I want output as:
Student_name
John
Jim
Johny
Tom
Jack
The query must support MS Access. as i'm fetching the data in html file and I've attached that html file to MS Aacess database
Sorry, but MS Access doesn't provide functionality to run query in recursive mode as CTE does. It's possible to use VBA macro to proceed through the collection of students to split comma separated values into set of records ;)
Let say, you have got table Student with fields:
ID (numeric - integer),
Students (string - char)
Sample data:
Id Students
1 John, Jim, Johny, Tom, Jack
2 Paula, Robert, Tim, Dorothy
5 Frank, Ramona, Giorgio, Teresa, Barbara
19 Isabell, Eve, Ewelina, Tadit
You need to create another table to store results of macro.
CREATE TABLE CTE1
(
ID INT,
OrigValue CHAR(255),
SingleValue CHAR(255),
Remainder CHAR(255)
);
To add macro, please do the following steps:
go to Visual Basic code Pane
insert new module
copy below code and paste it into previously added module
move the mouse cursor into **ModifyMyData** procedure by clicking whenever inside its body
run code (F5)
Option Compare Database
Option Explicit
'need reference to Microsoft ActiveX Data Object 2.8 Library
Sub ModifyMyData()
Dim sSQL As String
Dim rst As ADODB.Recordset
Dim vArray As Variant
Dim i As Integer
'clear CTE table
sSQL = "DELETE * FROM CTE;"
CurrentDb.Execute sSQL
'initial query
sSQL = "INSERT INTO CTE (ID, OrigValue, SingleValue, Remainder)" & vbCr & _
"SELECT ID, Students AS OrigValue, TRIM(LEFT(Students, InStr(1,Students,',')-1)) AS SingleValue, " & _
"TRIM(RIGHT(Students,LEN(Students)-InStr(1,Students,','))) AS Remainder" & vbCr & _
"FROM Student;"
CurrentDb.Execute sSQL
sSQL = "SELECT ID, OrigValue, SingleValue, Remainder" & vbCr & _
"FROM CTE"
Set rst = New ADODB.Recordset
rst.Open sSQL, CurrentProject.Connection, adOpenStatic
With rst
'fill rst object
.MoveLast
.MoveFirst
'proccess through the
Do While Not rst.EOF
'Split Remainder into array
vArray = Split(.Fields("Remainder"), ",")
'add every single value
For i = LBound(vArray) To UBound(vArray)
sSQL = "INSERT INTO CTE (ID, OrigValue, SingleValue, Remainder)" & vbCr & _
"VALUES(" & .Fields("ID") & ", '" & .Fields("OrigValue") & "','" & vArray(i) & "','" & GetRemainder(vArray, i + 1) & "');"
CurrentDb.Execute sSQL
Next
.MoveNext
Loop
.Close
End With
Set rst = Nothing
MsgBox "Ready!"
DoCmd.OpenTable "CTE"
End Sub
Function GetRemainder(vList As Variant, startpos As Integer) As String
Dim i As Integer, sTmp As String
For i = startpos To UBound(vList)
sTmp = sTmp & vList(i) & ","
Next
If Len(sTmp) > 0 Then sTmp = Left(sTmp, Len(sTmp) - 1)
GetRemainder = sTmp
End Function