SQL query works in access but not in excel - vba

I need to get data from a recordset. The SQL query works fine in MS Access and returns exactly the expected values, but when the same query is lunched in VBA Excel, I get the following error:
No value given for one or more required parameters
Do you have any ideas why this problem occurs?
Thank you.
Philippe-Olivier Roussel
Private Sub CBtype_AfterUpdate()
Dim strConnexion As String
Dim connexion As New ADODB.Connection
strConnexion = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & Database & ""
connexion.Open strConnexion
Dim rsMarque As New ADODB.Recordset
Dim seltype As String
seltype = CBtype.Value
rsMarque.Open "SELECT DISTINCT tblMarque.marque_nom FROM tblMarque, tblModele WHERE " & _
" tblMarque.marque_id = tblModele.marque_id AND tblModele.marque_id IN " & _
" (SELECT DISTINCT tblModele.marque_id FROM tblModele, tblType " & _
" WHERE tblModele.type_id = tblType.type_id AND tblModele.type_id = " & _
" (SELECT tblType.type_id FROM tblType WHERE " & _
" (tblType.type_nom = " & seltype & ")))", connexion, adOpenStatic
rsMarque.MoveFirst
With UserForm2.CBmarque
.Clear
Do
.AddItem rsMarque!marque_nom
rsMarque.MoveNext
Loop Until rsMarque.EOF
End With
End Sub

This error message looks like an output from the DBMS rather than Excel
I think you might be missing the apostrophe before and after your string variable. See if
" (tblType.type_nom = '" & seltype & "')))" works (I'm assuming the column you're querying is varchar type, since you declared seltype as string)

Related

SQL on VBA: Compilation error, a function or variable was expected

I have the code below but it isnt working. It gives me the error: Compilation error, a function or variable was expected.
I guess the error is on the Database.Execute method, but I didnt come with a solution yet.
Sub ChavesMontante()
Dim dbschaves As Database
Dim rschaves As DAO.Recordset
Dim tipodechave As String
Dim SQLCMD As String
Dim chave As String
Set dbschaves = CurrentDb
chave = "BED20777"
SQLCMD =
"(SELECT us.instalacao, ch.bloco, us.tipounidade " & _
"FROM (SELECT useccionadora, bloco " & _
"FROM sgdprd.redeprimaria rp " & _
"WHERE rp.useccionadora IS NOT NULL " & _
"CONNECT BY rp.nox = PRIOR rp.fontex AND rp.noy = PRIOR rp.fontey " & _
"START WITH rp.useccionadora = '" & chave & "' ) ch " & _
"INNER JOIN sgdprd.useccionadora us ON ch.useccionadora= us.instalacao) "
Debug.Print SQLCMD
Set rschaves = dbschaves.Execute(SQLCMD)
End Sub
Execute is used for action SQL statements (UPDATE, DELETE, INSERT), not to set a Recordset object.
Try the following changes:
Dim dbschaves As DAO.Database
...
Set rschaves = dbschaves.OpenRecordset(SQLCMD)
Also, remove the outer parens enclosing the entire SQL statement. I have never seen CONNECT BY PRIOR START WITH. Does the query open in Access?

Reference userform data in excel vba sql statements?

I'm trying to reference userform data in SQL queries in excel 2010. When running the following code as my form submit action, I get an error that one or more parameters have not been provided in the SQL query.
Private Sub SubmitButton_Click()
Dim Connection As ADODB.Connection
Dim ConnectionString As String
ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source=I:\DB.xlsx; Extended Properties=""Excel 12.0 Xml; HDR=YES"";"
Dim SQL As String
'Transfer information
SQL = "INSERT INTO [Tests$]" & _
"(PartNo, RootCause, CorrectiveAction, AssignedTo, Verification, Comments, DateOpened, DateClosed, " & _
"Status, Purpose, ProdDate, ShipDate, TestDate, SampleDate, CusName, Facility, Result, Wire, StartingDia, " & _
"WireType, IncomingDia, FailMode, RootCauseDetail)" & _
"VALUES" & _
"([Forms][frmTesting]![PartNo], [Forms][frmTesting]![RCause], [Forms][frmTesting]![Corrective], " & _
"[Forms][frmTesting]![Assigned], [Forms][frmTesting]![Verification], [Forms][frmTesting]![Comments], " & _
"[Forms][frmTesting]![OpenDate], [Forms][frmTesting]![CloseDate], [Forms][frmTesting]![Status], " & _
"[Forms][frmTesting]![Purpose], [Forms][frmTesting]![ProdDate], [Forms][frmTesting]![ShipDate], " & _
"[Forms][frmTesting]![TestDate], [Forms][frmTesting]![SampleDate], [Forms][frmTesting]![Customer], [Forms][frmTesting]![Facility], " & _
"[Forms][frmTesting]![Result], [Forms][frmTesting]![Wire], [Forms][frmTesting]![StartingDia], " & _
"[Forms][frmTesting]![WireType], [Forms][frmTesting]![IncomingDia], [Forms][frmTesting]![FailMode], [Forms][frmTesting]![RCDetail])"
Set Connection = New ADODB.Connection
Call Connection.Open(ConnectionString)
Call Connection.Execute(SQL, , CommandTypeEnum.adCmdText Or ExecuteOptionEnum.adExecuteNoRecords)
Connection.Close
Set Connection = Nothing
End Sub
Am I using the correct form object reference syntax for SQL queries? Is there a difference between Excel and Access with how to reference form data?
In case any viewers run across the same issue and are interested. I found the easiest solution to be something like SQL = "INSERT INTO [Tests$] (PartNo) Values ('" & frmTesting.PartNo & "')"

Run Time error 3061 Too Few parameters. Expected 6. Unable to update table from listbox

All,
I am running the below SQL and I keep getting error 3061. Thank you all for the wonderful help! I've been trying to teach myself and I am 10 days in and oh my I am in for a treat!
Private Sub b_Update_Click()
Dim db As DAO.Database
Set db = CurrentDb
strSQL = "UPDATE Main" _
& " SET t_Name = Me.txt_Name, t_Date = Me.txt_Date, t_ContactID = Me.txt_Contact, t_Score = Me.txt_Score, t_Comments = Me.txt_Comments" _
& " WHERE RecordID = Me.lbl_RecordID.Caption"
CurrentDb.Execute strSQL
I am not sure but, you can try somethink like that
if you knom the new value to insert in the database try with a syntax like this one
UPDATE table
SET Users.name = 'NewName',
Users.address = 'MyNewAdresse'
WHERE Users.id_User = 10;
Now, if you want to use a form (php)
You have to use this
if(isset($_REQUEST["id_user" ])) {$id_user = $_REQUEST["id_user" ];}
else {$id_user = "" ;}
if(isset($_REQUEST["name" ])) {$name= $_REQUEST["name" ];}
else {$name = "" ;}
if(isset($_REQUEST["address" ])) {$address= $_REQUEST["adress" ];}
else {$adress= "" ;}
if you use mysql
UPDATE table
SET Users.name = '$name',
Users.address = '$adress'
WHERE Users.id_User = 10;
i don't know VBA but I will try to help you
Going on from my comment, you first need to declare strSQL as a string variable.
Where your error expects 6 values and access doesn't know what they are. This is because form objects need to be outside the quotations of the SQL query, otherwise (as in this case) it will think they are variables and obviously undefined. The 6 expected are the 5 form fields plus 'strSQL'.
Private Sub b_Update_Click()
Dim db As DAO.Database
dim strSQL as string
Set db = CurrentDb
strSQL = "UPDATE Main" & _
" SET t_Name = '" & Me.txt_Name & "'," & _
" t_Date =#" & Me.txt_Date & "#," & _
" t_ContactID =" & Me.txt_Contact & "," & _
" t_Score =" & Me.txt_Score & "," & _
" t_Comments = '" & Me.txt_Comments & "'," & _
" WHERE RecordID = '" & Me.lbl_RecordID.Caption & "';"
CurrentDb.Execute strSQL
end sub
Note how I have used double quotes to put the form fields outside of the query string so access knows they aren't variables.
If your field is a string, it needs encapsulating in single quotes like so 'string'. If you have a date field it needs encapsulating in number signs like so #date# and numbers/integers don't need encapsulating.
Look at the code I have done and you can see I have used these single quotes and number signs to encapsulate certain fields. I guessed based on the names of the fields like ID's as numbers. I may have got some wrong so alter where applicable... Or comment and I will correct my answer.

VB.NET Update to Excel

I am developing an application in Visual Basic using Visual Studio 2013. In this application I am attempting to use an oledb UPDATE to write data out to an Excel spreadsheet treated as a database. I have tried numerous different formats of this but I either get a syntax error or it pretends to work but nothing actually gets written to the file. Can anyone tell me what is wrong with this code:
Public Function WriteToExcel(ExcelPath As String, dtUser As DataTable)
Dim vOffice As String = dtUser.Rows(0).Item("Office").ToString
Dim vDivision As String = dtUser.Rows(0).Item("Division").ToString
Dim vSection As String = dtUser.Rows(0).Item("Section").ToString
Dim vUser As String = dtUser.Rows(0).Item("UserID").ToString
Dim ExcelconnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ExcelPath & ";Extended Properties='Excel 12.0 Xml;HDR=YES';"
Dim BatchID As Long = 0
Dim sql As String = "UPDATE [InstallationReport$] SET Office = #uOffice WHERE [Primary User] = #uUser"
'Dim sql As String = "UPDATE [InstallationReport$] SET Office = #uOffice, " & _
'"Division = #uDivision, " & _
'"Section = #uSection " & _
'"WHERE [Primary User] = #uUser"
Using conn As New OleDb.OleDbConnection(ExcelconnString)
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#uOffice", vOffice)
cmd.Parameters.AddWithValue("#uDivision", vDivision)
cmd.Parameters.AddWithValue("#uSection", vSection)
cmd.Parameters.AddWithValue("#uUser", vUser)
Try
MessageBox.Show("Attempting to update " & vUser & ". " & vOffice & ", " & vDivision & ", " & vSection & "!")
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message & vbNewLine & ex.StackTrace)
End Try
End Using
End Function
Your SQL has two issues:
OleDbCommands use question marks ? as the placeholder for parameters, not #parameterName (that's for SqlCommands).
Section is a reserved keyword, so it needs to be escaped: [Section].

'if exist' SQL query in VBA with ADODB database connection

I need to uplad data from excel into a database, but I need to check first if there is data in the table for each upload so that I Update or Insert data.
To diferentiate Update or Insert, I'm usign a SQL IF EXIST command, which works okay in SQL. When I try this in Excel VBA I get an error message: "Command text was not set for the command object."
See code below
Dim strSQL As String
Dim Value As String
Dim Reference As String
Set RCconn = New ADODB.Connection
Set TuneCMD = New ADODB.Command
' Establish Recordset
Set Results = New ADODB.Recordset
'Establish a Connection
With RCconn
.Provider = "SQLOLEDB"
.ConnectionString = ConStr
End With
'Open the connection
RCconn.Open
'i Columns
For i = 5 To 10 '16
'j rows
For j = 6 To 60 '145
Value= Sheets("Value").Cells(j, i)
Reference= "W_F/P_" & Sheets("Reference").Cells(j, i)
stringTest = "IF EXISTS (SELECT * FROM UploadTable WHERE Ref = '" & Reference & "') "
stringTest = stringTest & "UPDATE Val "
stringTest = stringTest & "SET Val = '" & Value & "' "
stringTest = stringTest & "where Ref = '" & Reference & "' "
stringTest = stringTest & "Else "
stringTest = stringTest & "INSERT INTO UploadTable (Val , Ref ) "
stringTest = stringTest & "values ('" & Value & "', '" & Reference & "')"
RCconn.Execute strSQL
Next
Next
Set Results = Nothing
RCconn.Close
Set RCconn = Nothing
Is it the case that 'IF EXIST' can not be used in VBA? Is there a work around?
Thanks
ADODB.Connection.Execute sends a pass-through query to your database. It doesn't matter what SQL statement was in that string; if your database can understand it, it will be executed.
So inspect your SQL query again.
Try this:
Put a breakpoint on the line RCconn.Execute strSQL. When the debugger breaks there, inspect the value of strSQL. Copy it and execute in SQL Server Management Studio directly. If that doesn't work, correct your code that builds that string. If it works, then there is some problem with your ConnectionString. In that case, check that the userID and password you are using in the ConnectionString to connect has adequate privileges.