VB6 change value from positive to negative within a msaccess query - ms-access

I am so sorry for bothering you with maybe a fundamental and easy question; I need to change a positive value to a negative, this value is in the table (MSACCESS) I can´t figure out how to do it. I have been playing with the symbols but still nothing. The code is here:
Qry = "UPDATE QuickCash SET Pagado = 'S', TipoPago = '" & PymntType & "' Cantidad = '" & (Abs(Cantidad) * -1) & "' WHERE Folio = '" & grdDataGrid.Columns(0).Text & "'"
I have been querying, then changing and then updating but that isn't very pleasant...
Thank you in advance

I found out the issue, I missed a semicolon and the use of symbols was wrong. Here is the correct code.
Qry = "UPDATE QuickCash SET Pagado = 'S', TipoPago = '" & PymntType & "' , Cantidad = (Abs(Cantidad) * -1) " _
& "WHERE Folio = '" & grdDataGrid.Columns(0).Text & "'"
Sorry for the inconvenience, I hope this code can help someone else.
Thank you.

Related

Multi Criteria Dsum

Im starting to pull my hair out.
I am looking to do a multi criteria dsum that looks at the current user and todays date.
Tried many variations but must be missing something very simple so any help is appreciated
StatusBox = DSum("[Task_time]", "[tbl_Data]", "[CDP] = '" & Environ("username") & "' and [Record_Date] = '" & Date & "'")
Dates must be enclosed with #. Also they need to be formatted in order to return the desired result.
Try this:
StatusBox = DSum("[Task_time]", "[tbl_Data]", "[CDP] = '" & Environ("username") & "' and [Record_Date] = #" & Format(Date, "mm/dd/yyyy") & "#")
You are just making it slightly too complicated:
StatusBox = DSum("[Task_time]", "[tbl_Data]", "[CDP] = '" & Environ("username") & "' And [Record_Date] = Date()")

updating table via SQL with variables

I'm trying to update a table, via docmd.RunSql, and can't get it to update.
idlook = DLookup("[ID]", "119_review", "[todays_date] = #" & Format("" & Me.Combo87 & " " & Me.Combo89 & " 20" & Me.Combo91 & "", Medium) & "#")
MySQL = "UPDATE 119_review SET [Earned_Income]=" & Val(EarnedIncome) & " AND [Earned_income_withcal]=" & Val(EarnedIncomeCal) & " WHERE [ID]= " & idlook & ";"
Debug.Print MySQL
DoCmd.RunSQL MySQL
I've tried it both with and without brackets on the fields, the immediate window reads:
UPDATE 119_review SET Earned_Income=62 AND Earned_income_withcal=58.4 WHERE ID= 23;
UPDATE 119_review SET [Earned_Income]=62 AND [Earned_income_withcal]=58.4 WHERE [ID]= 23;
any idea where I'm going wrong?
You've made a simple syntax error.
Different columns in an update statement should be separated by ,, not by AND.
Weirdly enough, doing this wrong doesn't throw a syntax error, but just doesn't update anything.
Change the row setting your SQL string to the following:
MySQL = "UPDATE 119_review SET [Earned_Income]=" & Val(EarnedIncome) & " , [Earned_income_withcal]=" & Val(EarnedIncomeCal) & " WHERE [ID]= " & idlook & ";"

Getting a Key Violation Error when trying to use an Update String from a form

I have a form that allows people to add new employees but they need to be able to edit or update the existing employees as well.
So I added a button to allow them to make changes right on the form, click the update button and the record they were working on would be updated right away.
When I tested it however the string runs and even pops up a warning letting you know you are about to permanently change a record. But then it throws up an error stating "did not update record due to Key Violation"
I have included my "On Click" Event code
DoCmd.RunSQL "UPDATE EntList " & _
"SET EntList.BusinessUnit = '" & Me.cboBUnit & "', EntList.EntityName = '" & Me.txtEntName & "', EntList.Position = '" & Me.txtPos & "', EntList.Location = '" & Me.cboLoc & "', EntList.Client = '" & Me.cboClient & "', EntList.Dept = '" & Me.cboDept & "', EntList.DistKey = '" & Me.txtDistKey & "', EntList.Salary = '" & Me.txtSalary & "', Entlist.Currency = '" & Me.cboCurrency & "', EntList.[SG&A] = '" & Me.txtSG_A & "', EntList.BillRate = '" & Me.txtBillRate & "', EntList.[Util%] = '" & Me.txtUtil_ & "', EntList.MeritDate = '" & Me.txtMeritDate & "', EntList.[Merit%] = '" & Me.txtMerit_ & "' " & _
"WHERE EntList.EntityID = '" & Me.txtEntID.Value & "';"
I am wondering what I am missing that is causing this error.
If I followed the comments correctly, you have resolved the key violation error which occurred because one of the update values did not satisfy the requirement of a defined relationship which enforces referential integrity. In that situation, Access reports the relationship violation as key violation.
And, with that problem resolved, you're now facing a type mismatch between an update value and the destination field.
Your UPDATE included quotes around every value it supplied. Likely the current error is because a destination field is numeric data type instead of text.
So you can examine the data type of each destination field and make sure your UPDATE includes quotes around the values for text fields, # around the values for Date/Time fields, and no delimiters around the values for numeric fields.
While that is possible, it's also time-consuming and error-prone. A better approach is to use a parameter query so you needn't fiddle with delimiters.
Here is an abbreviated sample of the approach I'm suggesting. You will have to extend it to include the other fields I left out.
Dim strUpdate As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
strUpdate = "UPDATE EntList AS e" & vbCrlf & _
"SET e.BusinessUnit = pBusinessUnit, " & _
"e.EntityName = pEntityName" & vbCrLf & _
"WHERE e.EntityID = pEntityID;"
Debug.Print strUpdate
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strUpdate)
qdf.Parameters("pBusinessUnit") = Me.cboBUnit.Value
qdf.Parameters("pEntityName") = Me.txtEntName.Value
qdf.Parameters("pEntityID") = Me.txtEntID.Value
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing

Building a DCount/SQL statement in VBA via concetenation if test is true

I have a data entry form (Access 2007) which is designed to find out if the captured animal already has an existing WHno. Unfortunately, the data is messy and these is not a single unique identifier so several tests must be performed to narrow the search.
The animal could have 1 to 10 different pieces of information which will help identify the animal’s existence in the database. (The script only tests for about half of them thus far) I was thinking the best way to do this would to be to “build” a DCount and/or SQL statement based on which fields the user selects. I hope test to see if a particular text field box (unbound) has been filled out, and if yes, concatenate that section of code to the DCount/SQL statement, then move on to the next text field box to test.
Once the statement has been completely built, I want to test to see how many records have been counted/selected. If one record has been selected, I want to display the results in FormA. If 2 or more records are found, I want to display the records in a multi-listing form (FormB) from which the user can select the correct animal based on additional information not tested but displayed in FormB. If zero records are found, I want to create a new record with the data entered into the form updated into the table.
The hurdle I am struggling with now is building the DCount statements. I keep getting syntax errors . I do not know how to put this together piecemeal when the function bombs out because the syntax is incomplete (which it will be until I finish “building” it.)
I know the data is a mess. The scene out in the field is chaotic, different people gather different kinds of information, and not all the data that should be entered on the paper forms get filled out completely - if at all. The data gathering procedures are unlikely to change anytime soon.
Ideas? A different but easier approach idea is also welcome. New to this and not sure of all my programming options.
Also, how long can this statement be before it bombs out?
Code so far:
Private Sub GenerateWHno_Click()
Dim rs As DAO.Recordset
If IsNull(Forms!F_HotelEntry!txtSpecies) Or (Forms!F_HotelEntry!txtSpecies) = "" Then
MsgBox "Species is a required field. Please enter a species"
Exit Sub
End If
MsgBox txtSpecies
' Each line of code below indicates a data entry field(s) that needs testing and appended to SpeciesCount if "true". The first line is unchanging and is declared upfront.
'SpeciesCount = DCount("[Species]", "AnimalInfo", "(nz([Status])= '' OR [Status] = 'Alive' OR [Status] = 'Unknown') AND ([Species]= '" & txtSpecies & "')" _
' & "AND (((nz([L_ET_Color1])= '" & Nz(txtL_ET_Color1) & "' AND nz([L_ET_No1])= '" & nz(txtL_ET_No1) & "')" _
' & "AND (((nz([R_ET_Color1])= '" & Nz(txtR_ET_Color1) & "' AND nz([R_ET_No1])= '" & nz(txtR_ET_No1) & "')" _
' & "AND nz([L_ET_No2])= '" & nz(txtL_ET_No2) & "')" _
' & "AND nz([R_ET_No2])= '" & nz(txtR_ET_No2) & "')" _
' & "")
'If txtL_ET_Color Is Not Null Or txtL_ET_No Is Not Null Then
'LET1 = & "AND (((nz([L_ET_Color1])= '" & Nz(txtL_ET_Color1) & "' AND nz([L_ET_No1])= '" & nz(txtL_ET_No1) & "')" _
'Species Count = SpeciesCount & LET1
'End If
'If txtR_ET_Color Is Not Null Or txtR_ET_No Is Not Null Then
'RET1 = & "AND (((nz([R_ET_Color1])= '" & Nz(txtR_ET_Color1) & "' AND nz([R_ET_No1])= '" & nz(txtR_ET_No1) & "')" _
'Species Count = SpeciesCount & RET1
'End If
'If txtL_ET_No2 Is Not Null Then
'LET2 = AND nz([L_ET_No2])= '" & nz(txtL_ET_No2) & "')" _
'Species Count = SpeciesCount & LET2
'End If
'If txtR_ET_No2 Is Not Null Then
'RET2 = AND nz([R_ET_No2])= '" & nz(txtR_ET_No2) & "')" _
'Species Count = SpeciesCount & RET2
'End If
'There are about 4 more options/fields to add to the script but you get the idea.
'Thus: If user selected Species, and filled out L_ET_Color1 and/or L_ET_No1, the final concatenation (DCount statement)would look like this:
SpeciesCount = DCount("[Species]", "AnimalInfo", "([Status]= 'Alive' OR [Status] = 'Unknown' OR nz([Status]) = '') AND [Species]= '" & txtSpecies & "' AND (nz([L_ET_Color1])= '" & Nz(txtL_ET_Color1) & "' AND nz([L_ET_No1])= '" & Nz(txtL_ET_No1) & "')")
If SpeciesCount > 1 Then
MsgBox SpeciesCount & " Greater than 1. Please select correct animal"
'Create SQL statement that mimics DCount statement and display all fields from AnimalInfo table as multilisting to select from
ElseIf SpeciesCount = 0 Then
MsgBox "You need a new WHno"
WHno = Nz(DMax("WHno", "AnimalInfo")) + 1
MsgBox WHno
Set rs = CurrentDb.OpenRecordset("AnimalInfo")
rs.AddNew
rs!WHno = WHno
rs!Species = txtSpecies
rs!L_ET_Color1 = txtL_ET_Color1
rs!L_ET_No1 = txtL_ET_No1
rs.Update
rs.Close
Else
'Create SQL statement that mimics DCount statement and display all fields from AnimalInfo table as single listing in a form.
MsgBox "You're WHno is " & WHno & " Is this the correct WHno?"
End If
Forms!F_HotelEntry!txtSpecies = ""
Forms!F_HotelEntry!txtL_ET_Color1 = ""
Forms!F_HotelEntry!txtL_ET_No1 = ""
End Sub
I would suggest to first compose the condition into a string variable. There you can print its content via Debug.Print and see what the problem might be.
If you cannot spot the problem via inspection alone, paste the generated string to the Sql view of a proper query and see if Access gives you helpful information on switching to design view.

Parameterized query in ADO - add data into database

Bit of a newbie to vbscript, not particularly fond of it but my client uses it so I can't do much about it! I'm having trouble using parameterized queries to add data into the database! Please save me guys!!
So far, the existing code is
function ecaddupdateDEV (thistable, idvar, vararray)
for each varname in vararray
valstring = valstring & ", session(""" & varname & """)"
thesefields = thesefields & ", " & varname
next
thesefields = idvar & thesefields
valstring = " array( " & ecremovel(valstring, 2) & ")"
vals = eval(valstring)
set temprs = Server.CreateObject("ADODB.RecordSet")
if session(idvar) = 0 then
'response.Write("chid is 0 add new record")
' ADD THIS REC
temprs.open thistable, db,1,3,2
temprs.AddNew vararray, vals
ecaddupdateDEV = temprs(idvar)
temprs.close
set temprs = ecquery("select " & idvar & " from " & thistable & " order by " & idvar & " desc ")
ecaddupdateDEV = temprs(idvar)
else
' UPDATE THIS REC
selectclause = "select " & thesefields & " from " & thistable & " where " & idvar & " = " & session(idvar)
temprs.open selectclause, db ,1,3
temprs.update vararray, vals
ecaddupdateDEV = temprs(idvar)
temprs.close
end if
set temprs = nothing
end function
The temprs variable I want to make parameterized for security purposes, obviously lol! I just have no clue how to do it! What I've read I just found confusing, please help!! Many thanks in advance!
Instead of a Recordset, use a Command. Here's the example, that will get you going, but you may have to tweak it, as from experience, named parameters don't really work, so you assign their value in the order in which they appear in the SQL statement.
How To Call a Parameterized Query to an Access Database with ADO