VBA Assign a RecordSet Field to a ComboBox - vba

I have the following code:
sSQL = "SELECT CODER FROM " & dbfname & " IN " & dir & " WHERE TRIM(CODEK) = TRIM(kCode)"
Combo29.RowSource = sSQL
Combo29.Requery
, where "CODER" is a field in the dbf file. "CODEK" is also a field in that dbf file, which im comparing with the string kCode.
When I run the code and when I click on the combobox, it asks me to enter arguments instead of showing the selected arguments. The RowSource type is set to Table/Query.
Is the assigning statement incorrect and how can I modify it to show me list of results from the SQL statement?

If I understand your problem correctly kCode is a string in VBA so you'll have to set up your SQL string the following way
sSQL = "SELECT CODER FROM " & dbfname & " IN " & dir & " WHERE TRIM(CODEK) = TRIM('" & kCode & "')"`

Related

Microsoft Access VBA code with Select SQL String and Where clause

I'm using Microsoft Access to develop a database app. An important feature the user would need is to automatically send an email update to all relevant stakeholders.
The problem is that I'm getting
Run-time error '3075' Syntax error in query expression.
Here it is below:
Set rs = db.OpenRecordset("SELECT StakeholderRegister.[StakeholderID], StakeholderRegister.[ProjectID], StakeholderRegister.[FirstName], StakeholderRegister.[LastName], StakeholderRegister.[EmailAddress] " & _
" FROM StakeholderRegister " & _
" WHERE (((StakeholderRegister.[ProjectID]=[Forms]![ChangeLog]![cboProjectID.Value])) ;")
Funny thing is that I created a query table on Access to create the relevant recordset and the turned on SQL view to copy the exact sql string that's above. That query works however it opens an Input Parameter box, whereas this code should be using the value typed into a forms text box as a matching criteria.
To use a variable as a parameter, do not include it within the quotes:
" WHERE StakeholderRegister.[ProjectID]=" & [Forms]![ChangeLog]![cboProjectID].[Value]
or just
" WHERE StakeholderRegister.ProjectID=" & Forms!ChangeLog!cboProjectID.Value
Note: You really only need the square brackets when there is something like a space in the name, which is not the best practice anyway.
I also took the liberty to remove the parentheses, as they are not needed in such a simple WHERE clause, and can cause more trouble than they are worth.
Try,
Dim strSQL As String
strSQL = "SELECT StakeholderRegister.[StakeholderID], StakeholderRegister.[ProjectID], StakeholderRegister.[FirstName], StakeholderRegister.[LastName], StakeholderRegister.[EmailAddress] " & _
" FROM StakeholderRegister " & _
" WHERE StakeholderRegister.[ProjectID]=" & [Forms]![ChangeLog]![cboProjectID].Value & " ;"
Set rs = Db.OpenRecordset(strSQL)
if [ProjectID] field type is text then
Dim strSQL As String
strSQL = "SELECT StakeholderRegister.[StakeholderID], StakeholderRegister.[ProjectID], StakeholderRegister.[FirstName], StakeholderRegister.[LastName], StakeholderRegister.[EmailAddress] " & _
" FROM StakeholderRegister " & _
" WHERE StakeholderRegister.[ProjectID]='" & [Forms]![ChangeLog]![cboProjectID].Value & "' ;"
Set rs = Db.OpenRecordset(strSQL)

How to delete rows in ms access VBA based on multiple attributes

How do I delete rows in ms access VBA based on multiple attributes?
I have written the code below, but it doesn't seem to work.
CurrentDb.Execute "DELETE * FROM StaffAtMeeting" & _
"WHERE RoomID =& Me.field1 AND MeetingDate = Me.field2 AND MeetingTime = Me.field3;"
Maybe I am missing some " (Double Quotes) and some & (Ampersands) ?
You are missing open/close " (Double Quotes) and some & (Ampersands)
currentdb.execute "DELETE * " & _
"FROM StaffAtMeeting " & _
"WHERE(((RoomID) =" & me.field1 & " AND (MeetingDate) =#" & me.field2 & "# AND (MeetingTime) =#" & me.field3 & "#));"
When you write a string statement in VBA you need an opening and closing double quotes, the ampersand acts as a concatenation. The underscore lets the code know to continue on the next line.
Since your variables are not part of the string, you have to end the string, concatenate the variable, then reopen the string. The # (pound sign/hash tag/Number sign) signifies SQL you are using a date or time.

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.

Append string to record

Environement : Oracle 11gR2 , ASP .Net, VB
Aim: need to append text string to an existing record.
Problem: When using the following
strSQL += "Update table_name SET "
strSQL += " JOB = '" & Trim(Me.txtjob.Text) & "',"
strSQL += " NAME = '" & Trim(Me.txtname.Text) & "',"
strSQL += " REMARK = REMARK || ' " & Trim(Me.txtremark.Text) & "'"
It appends the already existing data along with the new data to the new data.
Example:
Contents before SQL Execution: ABC
Contents to append: DEF
Result after execution : ABCABCDEF
expected result: ABCDEF
I tried to use a few permutations to get the right result but to no avail.
Any suggestions/resolution will be appreciated.
Okay, it seems that this was a rather straight forward solution which i ended up over complicating.
IN my case:
I was reading the record and displaying it in a text box.
What i ended up doing was :
just update the entire contents of the text box again to the record.
Thus overwriting the already existing contents along with the modified contents of the textbox.
strSQL += " DOC_LOCATION = '" & System.Web.HttpUtility.HtmlEncode(Trim(Me.txtremark.Text)) & (" Last Edit: ") & temp & " " & DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") & "'"
Since this was a rather simple application, this solution worked for me.

Access Query SQL Type mismatch error when trying to update query via VBA

I have a query that takes multiple criteria from comboboxes on a form.
In order to alter the sort of the query for reporting purposes I use the below code:
Dim oDB As Database
Dim oQuery As QueryDef
Set oDB = CurrentDb
Set oQuery = oDB.QueryDefs("qry_AdjustmentDataSplitGroup")
oQuery.SQL = ("SELECT tbl_AdjustmentData.POLICY, tbl_AdjustmentData.MD, tbl_AdjustmentData.[EFF DTE], tbl_AdjustmentData.NAME, tbl_AdjustmentData.[DEP/PREM], tbl_AdjustmentData.[LST PREM], tbl_AdjustmentData.GROUP, tbl_AdjustmentData.[WA DATE] FROM tbl_AdjustmentData WHERE (((tbl_AdjustmentData.Group) Is Not Null)) ORDER BY tbl_AdjustmentData.[WA DATE];")
Set oQuery = Nothing
Set oDB = Nothing
And change the ORDER BY depending on what button is pressed on the form. This works OK.
However, I thought it would be the same if I needed to alter the query criteria (or the WHERE) I just change that line like I can change the ORDER BY part of the code.
When I use the below code for a different query:
Dim oDB As Database
Dim oQuery As QueryDef
Set oDB = CurrentDb
Set oQuery = oDB.QueryDefs("qry_AdjustmentDataSplitNonGroupApr")
oQuery.SQL = ("SELECT qry_AdjustmentDataSplitNonGroup.POLICY, qry_AdjustmentDataSplitNonGroup.MD, qry_AdjustmentDataSplitNonGroup.[EFF DTE], qry_AdjustmentDataSplitNonGroup.NAME, qry_AdjustmentDataSplitNonGroup.[DEP/PREM], qry_AdjustmentDataSplitNonGroup.[LST PREM], qry_AdjustmentDataSplitNonGroup.[WA DATE], Right([EFF DTE],2) & " / " & Mid([EFF DTE],5,2) & " / " & Left([EFF DTE],4) AS EffectiveDate, Right([WA DATE],2) & " / " & Mid([WA DATE],5,2) & " / " & Left([WA DATE],4) AS WADate, Left([EFF DTE],4) AS [Year], Left([WA DATE],4) AS WAYear FROM qry_AdjustmentDataSplitNonGroup WHERE (((Left([EFF DTE],4))=[Forms]![frm_Index]![cbo_YearPicker]) AND ((Left([WA DATE],4))=[Forms]![frm_Index]![cbo_WAPicker]) AND ((Mid([EFF DTE],5,2))=""04""));")
Set oQuery = Nothing
Set oDB = Nothing
I want to be able to remove this part:
AND ((Left([WA DATE],4))=[Forms]![frm_Index]![cbo_WAPicker])
Using an option button on the form, leaving the rest the same.
The problem though, is when I try this I get a 'Type mismatch' error on the line beginning oQuery.SQL.
I assume it's to do with the section where Mid([EFF DTE],5,2))=""04"" and I've tried double quotes as in this case, I've tried single quotes and I've tried no quotes at all changing the record in the Table from Text to Number, but always get the same error.
Is there an easier way to do this? Or can my code be ammended to work correctly?
Final note, the reason for the option button at all is to remove the 'WA Date' criteria from the query as that criteria reads from a combobox and when I fiddled with the combobox to allow an ALL option it actually returned no results.
I've heard that UNION ALL might be another way round this problem so as to avoid having to mess about removing the criteria altogether but I'm not sure how to implement that.
The situation you're facing is easy to misinterpret.
In your second code sample, you get a "type mismatch" error at the line similar to this abbreviated version:
oQuery.SQL = ("SELECT qry_AdjustmentDataSplitN ... ")
You might think that is Access complaining that your SELECT statement is not valid. But the actual problem is similar to this example from the Immediate window, which also throws a "type mismatch" error:
? "a" / "b"
That happens because you can't divide one string by another string. Division only makes sense with numerical values.
When you examine your code with that issue in mind, you should find multiple cases of this pattern:
"some text & " / " & more text"
Compare that to my "a" / "b" example.
You need to quote it differently. I will take a stab at what I think you want. I'm unsure whether the statement logic is correct, but at least this produces a valid VBA string:
Dim strSelect As String
strSelect = "SELECT q.POLICY, q.MD, q.[EFF DTE], q.NAME, " & _
"q.[DEP/PREM], q.[LST PREM], q.[WA DATE], " & _
"(Right([EFF DTE],2) & '/' & Mid([EFF DTE],5,2) & '/' & Left([EFF DTE],4)) AS EffectiveDate, " & _
"(Right([WA DATE],2) & '/' & Mid([WA DATE],5,2) & '/' & Left([WA DATE],4)) AS WADate, " & _
"Left([EFF DTE],4) AS [Year], Left([WA DATE],4) AS WAYear" & vbCrLf & _
"FROM qry_AdjustmentDataSplitNonGroup AS q" & vbCrLf & _
"WHERE Left([EFF DTE],4)=[Forms]![frm_Index]![cbo_YearPicker]" & vbCrlf & _
"AND Mid([EFF DTE],5,2)='04';"
Debug.Print strSelect ' <-- view the completed statement text in Immediate window
' Ctrl+g will take you there
oQuery.SQL = strSelect
And finally, reading between the lines, I'm guessing your EFF DTE and WA DATE values are dates as text in yyyy/mm/dd format and you want the query to display them in dd/mm/yyyy format. If that is true, compare these two expressions which should both return the same string:
Right([EFF DTE], 2) & '/' & Mid([EFF DTE], 5, 2) & '/' & Left([EFF DTE], 4)
Format([EFF DTE], 'dd/mm/yyyy')