Search Functionality RunTime error 424 at Select - ms-access

My requirement: To search for data in database, using VB forms and 3 text boxes.
1 TextBox, I will give Input (UserName)
1 TextBox for Location
1 TextBox for displaying output
My code is
Private Sub CommandButton3_Click()
Dim Cn As ADODB.Connection '* Connection String
Dim oCm As ADODB.Command '* Command Object
Dim sName As String
Dim rs As ADODB.Recordset
Dim uname As String
Set Cn = New ADODB.Connection
Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
Cn.ConnectionTimeout = 40
Cn.Open
Set oCm = New ADODB.Command
oCm.ActiveConnection = Cn
‘Record Set
Set rs = New ADODB.Recordset
‘Select Operation
rs.Open "SampleTable", Cn, adOpenKeyset, adLockPessimistic, adCmdTable
uname = rs("UserName")
rs.Open "Select * from SampleTable where uname = '" & text1.Text & "'", ActiveConnection, adOpenForwardOnly, adLockReadOnly, adCmdText
**'Display the Output in TextBox3**
TextBox3.Text = rs("UserName") + rs("Location")
rs.Close
Cn.Close
End Sub
I can understand the population of data is not happening so getting a RunTime error 424 at Select statement. How can I retrieve the data for the corresponding Input given?

You do not need to open the table; rs.Open "SampleTable" before searching it.
Not sure what this is for; uname = rs("UserName")
You should just run; rs.Open "Select * ... (Running the .Open on the same RS twice without closing the first is probably whats causing your error)
You should escape your input; replace$(text1.Text, "'", "''")
You should check for rs.EOF after the .open
Use & not + for concatenating strings
update
sub xxx
Dim Cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sName As String
Set Cn = New ADODB.Connection
Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
Cn.ConnectionTimeout = 40
Cn.Open
Set rs = New ADODB.Recordset
sName = replace$(text1.Text, "'", "''")
rs.Open "Select * from SampleTable where UserName = '" & sName & "'", Cn, adOpenForwardOnly, adLockReadOnly, adCmdText
if (rs.eof) then
msgbox "no match"
else
TextBox3.Text = rs("UserName") & " " & rs("Location")
rs.Close
end if
set rs = nothing
Cn.Close
set cn = nothing
end sub

Related

Type mismatch, opening a RecordSet

Getting this error all time:
Run-time error '13': Type mismatch.
On this line
rs.Open , sqlstr, conn
I tried everything and can't solve the problem. I'm trying to update one row in MySQL database.
Private Sub CommandButton3_Click()
Dim conn As New ADODB.Connection
Dim server_name As String
Dim database_name As String
Dim user_id As String
Dim password As String
Dim i As Long
Dim sqlstr As String
Dim table1 As String, table2 As String
Dim field1 As String, field2 As String
Dim rs As ADODB.Recordset
Dim vtype As Variant
server_name = "99.99.99.99"
database_name = "name"
user_id = "user"
password = "pass"
Set conn = New ADODB.Connection
conn.Open "DRIVER={MySQL ODBC 3.51 Driver}" _
& ";SERVER=" & server_name _
& ";DATABASE=" & database_name _
& ";UID=" & user_id _
& ";PWD=" & password _
& ";OPTION=16427"
Set rs = New ADODB.Recordset
sqlstr = "SET SQL_SAFE_UPDATES = 0; UPDATE table SET poslano = 'Poslano' WHERE poslano = 'Neposlano';"
rs.Open , sqlstr, conn
With Worksheets("List6").Cells("A1")
.ClearContents
.CopyFromRecordset rs
End With
skipextract:
On Error Resume Next
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
On Error GoTo 0
End Sub
The comma after rs.Open makes VBA "think" that the Source is omitted:
Thus, it gives Type mismatch error. Try to write it like this:
rs.Open sqlstr, conn

Excel VBA MySQL "SELECT * FROM table" not full informaton

I have a really weird issue with my Excel VBA code selecting values from a MySQL database. I structured a simple database with following columns:
ID
Name
Surname
City
And lets assume having following entrys:
01; Pan; Peter; NYC
02; P; Peter; NYC
But now the issue, if I select * from my table it shows me only following output:
01; P; Pan; NYC
02; P; Pan; NYC
That means the I only see the minimal lenght of an entry .... what is going on there? I have really casual VBA code in different modules for that task:
Public variables:
Public cn As ADODB.Connection
Public rs As ADODB.Recordset
Public strSql As String
Connection module:
Public Function connectDB()
Dim strServer_Name As String
Dim strDB_Name As String
Dim strUser_ID As String
Dim strPassword As String
With Sheet2
strServer_Name = .Range("B2").Value
strDB_Name = .Range("B3").Value
strUser_ID = .Range("B4").Value
strPassword = .Range("B5").Value
End With
Set cn = New ADODB.Connection
cn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver}" & _
";SERVER=" & strServer_Name & _
";DATABASE=" & strDB_Name & _
";UID=" & strUser_ID & _
";PWD=" & strPassword & ""
End Function
Sub module:
Sub request()
strSql = "SELECT * FROM test"
Call connectDB
Set rs = New ADODB.Recordset
rs.Open strSql, cn, adOpenDynamic
With Sheet1.Range("A1")
.ClearContents
.CopyFromRecordset rs
End With
Call disconnectDB
End Sub
Is this a VBA issue or are there any bugs in my MySQL?
Okay guys I've found a solution in this post: sql-query-doesnt-return-full-results-for-only-one-field
Solved it the same way the other guy did. In my code it looks like this:
Sub request()
Dim iCols As Integer
Dim iRows As Integer
strSql = "SELECT * FROM test"
Call connectDB
Set rs = New ADODB.Recordset
rs.Open strSql, cn, adOpenDynamic
iRows = 10
While Not rs.EOF
For iCols = 0 To rs.Fields.Count - 1
Tabelle1.Cells(iRows, iCols + 1).Value = rs.Fields(iCols).Value
Next
rs.MoveNext
iRows = iRows + 1
Wend
Call disconnectDB
End Sub
But thanks to everyone who tried to help me!

How to check for record by using ID, then if record exists update if not add new record

I've create an excel userform to collect data. I have connected it to Access to dump the data. However I want to update Access every time a user presses the submit button.
Basically I need the Select statement to determine an id existence, then if it doesn't exists I need to use the INSERT to add the new row. I'm very new with any SQL so any help would be great.
Here is the code I have now, I need to adapt it to ADO.
Sub Update()
Dim cnn As ADODB.Connection
Dim MyConn
Dim rst As ADODB.Recordset
Dim StrSql As String
Set cnn = New ADODB.Connection
MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open MyConn
Set rst = New ADODB.Recordset
rst.CursorLocation = adUseServer
rst.Open Source:="Foam", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdTable
StrSql = "SELECT * FROM Foam WHERE FoamID = " & txtMyID
Set rst = CurrentDb.OpenRecordset(StrSql, dbOpenDynaset)
If (rst.RecordCount = 0) Then
DoCmd.RunSQL "INSERT INTO Foam (ID, Part, Job, Emp, Weight, Oven) VALUES " & _
"(" & txtID & ", '" & txtField1 & "', '" & txtField2 & "', '" & txtField3 & "', '" & txtField4 & "', '" & txtField5 & "' );"
End If
' Close the connection
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
End With
End Sub
I revised your code sample just enough to get it working on my system and tested this version in Excel 2007.
When I use a value for lngId which matches the id of an existing record, that record is opened in the recordset and I can update the values of its fields.
When lngId does not match the id of an existing record, the recordset opens empty [(.BOF And .EOF) = True]. In that situation, I add a new record and add the field values to it.
Sub Update()
Const TARGET_DB As String = "database1.mdb"
Dim cnn As ADODB.Connection
Dim MyConn As String
Dim rst As ADODB.Recordset
Dim StrSql As String
Dim lngId As Long
Set cnn = New ADODB.Connection
MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open MyConn
End With
lngId = 4
StrSql = "SELECT * FROM tblFoo WHERE id = " & lngId
Set rst = New ADODB.Recordset
With rst
.CursorLocation = adUseServer
.Open Source:=StrSql, ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdText
If (.BOF And .EOF) Then
' no match found; add new record
.AddNew
!ID = lngId
!some_text = "Hello World"
Else
' matching record found; update it
!some_text = "Hello World"
End If
.Update
.Close
End With
Set rst = Nothing
cnn.Close
Set cnn = Nothing
End Sub
Using VBA, here is a sample of how to query for a certain ID to check if it exists. If it does not then add it via an INSERT statement:
Dim rs As DAO.Recordset
Dim StrSql As String
StrSql = "SELECT * FROM MyTable WHERE ID = " & txtMyID
Set rs = CurrentDb.OpenRecordset(StrSql, dbOpenDynaset)
If (rs.RecordCount = 0) Then
DoCmd.RunSQL "INSERT INTO MyTable (ID, Field1, Field2) VALUES " & _
"(" & txtID & ", '" & txtField1 & "', '" & txtField2 & "');"
End If

Add or Update data from Excel to MYSQL

I Have created a ODBC DSN to MySQL called "TEST". The table in the MySQL Database is Called "DETAILS" and the columns are called:
ID (Auto Number) | NAME | SURNAME | DATE|
In Excel, I have a userform with the following controls: Textbox1 = NAME, Textbox2 = SURNAME and DTPicker = DATE + a Command Button Called SAVE.
Is there a way that I can save this data directly to the MySQL Database by pushing the command button? I have the ODBC DSN connection to access the database
UPDATE
This is the code I Have:
Private Sub CommandButton1_Click()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strCon = "Driver={MySQL ODBC 5.1 Driver};SERVER=SERVERNAME;DATABASE=DATABASE;UID=USERID;PWD=PASSWORD"
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
Set rs = CreateObject("adodb.recordset")
rs.Open "INSERT INTO MYTABLE (ID, Name, Surname, Date) VALUES (Textbox1.Value, Textbox2.value, DTPicker1.Value)", cn
rs.Close
End Sub
But It doesn't allow me to reference the CONTROLS, Textboxes and DTPicker
Give this a shot:
Private Sub CommandButton1_Click()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strCon = "Driver={MySQL ODBC 5.1 Driver};SERVER=SERVERNAME;DATABASE=DATABASE;UID=USERID;PWD=PASSWORD"
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
Set rs = CreateObject("adodb.recordset")
rs.Open "INSERT INTO MYTABLE (Name, Surname, Date)" _
" VALUES (" & Textbox1.Value & ", " & Textbox2.value _
", " & DTPicker1.Value &")", cn
rs.Close
End Sub
Here is the Code to Make this work:
Private Sub CommandButton1_Click()
Dim c As ADODB.Connection
Dim r As ADODB.Recordset
Set c = New ADODB.Connection
Dim rw As Integer
c.Open "DSN=DSNName"
sq = "Insert into MYTABLE (NAME, SURNAME, DATE) values ('" & TextBox1.Value & "','" & TextBox2.Value & "','" & DTPicker1.Value & "')" Set r = c.Execute(sq)
c.Close
End Sub

Access Continuos Subform Repeating Information

Access Database Form1 is a Continuous Form that has an EmployeeID field you can double click to take you to another form that contains information about the Employee. In order to retain the correct employee I use this code...
Private Sub EmployeeID_DblClick(cancel as integer)
Dim myID as variant
myID = me.EmployeeID
DoCmd.OpenForm "frm_EmployeeInfo",,,,,,myID
End Sub
This Not only brings up the correct employee information but populates the number into a hidden textbox to retain the information.
On the Employee Form there is a TabControl with 4 tabs, one of the tabs contains a Continous subform that I am trying to populate employee information but instead of the information being populated down (let's say Employee X has 8 lines of different attributes to display) it is repeating the same one. Here is my code for the subform:
Option Compare Database
Private Sub Form_open(cancel As Integer)
Dim strConnection, strSQL As String
Dim conn As ADODB.Connection
Dim tbl As ADODB.Recordset
Dim SourceCode As String
Dim myID As Variant
Set conn = New ADODB.Connection
strConnection = "ODBC;Driver={SQLserver};DSN=AccessDatabase;Server=Labor;DATABASE=Source;Trusted_Connection=Yes;"
conn.Open strConnection
myID = CInt(Me.OpenArgs)
SourceCode= Nz(DLookup("[SourceCode]", "Locaton", "[LOC_ID] = Forms!frmUtility![Site].value"), "")
If SourceCode<> "" Then
strSQL = "SELECT EmployeeID,BenefitID,DeductionAmount,BenefitAmount,CoverageAmount,EffectiveDate,"
strSQL = strSQL & "EligibleDate,ExpirationDate FROM "
strSQL = strSQL & SourceCode & "_EmployeesBenefitsNew WHERE EmployeeID= " & myID
Else
strSQL = "SELECT EmployeeID,BenefitID,DeductionAmount,BenefitAmount,CoverageAmount,EffectiveDate,"
strSQL = strSQL & "EligibleDate,ExpirationDate FROM "
strSQL = strSQL & "EmployeesBenefitsNew WHERE EmployeeID= " & myID
End If
Set tbl = New ADODB.Recordset
With tbl
Set .ActiveConnection = conn
.Source = strSQL
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.Open
End With
With tbl
On Error Resume Next
.MoveFirst
Do Until tbl.EOF
Me.txtBenefitID.Value = tbl!BenefitID
Me.txtDeductionAmt.Value = tbl!DeductionAmount
Me.txtBenefitAmt.Value = tbl!BenefitAmount
Me.txtCoverageAmt.Value = tbl!CoverageAmount
Me.txtEffDt.Value = tbl!EffectiveDate
Me.txtTermDt.Value = tbl!ExpirationDate
Set Me.Recordset = tbl
.MoveNext
Loop
.Close
End With
conn.Close
Set conn = Nothing
Set tbl = Nothing
End Sub
Can anyone shed some light on this situation? Thanks!
You need to either set the recordset or the recordsource with the data, you cannot write to a continuous form on different lines, the lines only display as different if you have a recordset.
So
''********************
Set Me.Recordset = tbl
''********************
In you code:
Private Sub Form_open(cancel As Integer)
Dim strConnection, strSQL As String
Dim conn As ADODB.Connection
Dim tbl As ADODB.Recordset
Dim SourceCode As String
Dim myID As Variant
Set conn = New ADODB.Connection
strConnection = "ODBC;Driver={SQLserver};DSN=AccessDatabase;Server=Labor;DATABASE=Source;Trusted_Connection=Yes;"
conn.Open strConnection
myID = CInt(Me.OpenArgs)
SourceCode= Nz(DLookup("[SourceCode]", "Locaton", "[LOC_ID] = Forms!frmUtility![Site].value"), "")
If SourceCode<> "" Then
strSQL = "SELECT EmployeeID,BenefitID,DeductionAmount,BenefitAmount,CoverageAmount,EffectiveDate,"
strSQL = strSQL & "EligibleDate,ExpirationDate FROM "
strSQL = strSQL & SourceCode & "_EmployeesBenefitsNew WHERE EmployeeID= " & myID
Else
strSQL = "SELECT EmployeeID,BenefitID,DeductionAmount,BenefitAmount,CoverageAmount,EffectiveDate,"
strSQL = strSQL & "EligibleDate,ExpirationDate FROM "
strSQL = strSQL & "EmployeesBenefitsNew WHERE EmployeeID= " & myID
End If
Set tbl = New ADODB.Recordset
With tbl
Set .ActiveConnection = conn
.Source = strSQL
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.Open
End With
''********************
Set Me.Recordset = tbl
''********************
conn.Close
Set conn = Nothing
Set tbl = Nothing
End Sub