Clear Columns with Button vba - ms-access

This appears easy but has crushed me into posting this: I need to clear 5 columns with a button click. That's it. I do not need to delete the columns because they are used in a sum calculation. I just need to clear the values greater than zero.
Table Name is Customer
Column 1 = Week 1
Column 2 = Week 2
ETC
Here is my garbage code that does not run. Any help would be a great gesture this Holiday season. I am using Access 2016.
Private Sub Command80_Click()
Dim SQL As String
SQL = "UPDATE Customer " & _
"SET Week1 = NULL " & _
"WHERE Week 1 > 0"
DoCmd.RunSQL SQL
End Sub

If the field name to be updated is Week1 (and not Week 1) then this is the code:
Private Sub Command80_Click()
Dim sql As String
sql = "UPDATE Customer " & _
"SET Week1 = NULL " & _
"WHERE Week1 > 0"
DoCmd.RunSQL sql
End Sub
You've used Week 1 (with a blank) in your code.

If "Week 1" is the actual field name, wrap it in brackets:
"SET [Week 1] = NULL " & _
"WHERE [Week 1] > 0"

Related

Need help to update a sql table from excel sheet using vb script

Thank you in advance.
My aim is to update sql table from excel. So i wrote a vbscript to get sql table from my-sql to excel on a single click. Table looks like this:-
id rule length isactive date
1 rule 1 3 1 NULL
2 rule 2 5 0 NULL
3 rule 3 6 1 NULL
4 rule 4 7 1 8/10/2015
5 rule 5 3 0 NULL
Now i will update length, isactive, date fields and this data should be updated in the table on a single click. Please help me in this script. I tried update query which is failing with run time error-
80040e14.
part of script is
For iCount = 2 To 6
intRLength = CInt(objSheet.Cells(iCount, 3).Value)
intID = CInt(objSheet.Cells(iCount, 1).Value)
strQuerie = "UPDATE" & strDatabase & "." & strTable & "SET retentionlength=" & intRLenth & "where id= " & intID
rs.Open strQuerie ' --- Getting run time error- 80040e14 message here
Next
That's most probably because of spacing issue in some part of your formed query
Your query should rather look like
strQuerie = "UPDATE " & strDatabase & "." & strTable & " SET retentionlength=" & intRLenth & " where id= " & intID
Otherwise, as it stands; your query would look like below which clearly way wrong
UPDATEDB_NAME.TABLE_NAMESET retentionlength=somevaluewhere id= someid

How to filter a form with multi-Field in MS Access using VBA

I have the code below in a click button event in MS Access 2013 form, whose datasource is from a query with the following fields “EnrNo, FirstName, LastName, and RegDate”.
The form has three text boxes and a command button:
txtKeyword
txtDateFrom
txtDateTo
cmdSearch
The click button (cmdSearch) in the form is intended to filter the query based on three criteria’s , which could be any of the two “EnrNo, FirstName, LastName” AND the range of the date(s) entered in the text box txtDateTo and cmdSearch
My code successfully filters only EnrNo. Please help me out... Thanks for your time.
Private Sub cmdSearch_Click()
Dim strWhere As String 'The criteria string.
Dim Where As String
Dim lngLen As Long 'Length of the criteria string to append to.
Const conJetDate = "\#mm\/dd\/yyyy\#" 'The format expected for dates in a JET query string.
'Text field example. Use quotes around the value in the string.
If Not IsNull(Me.txtFilter) Then
strWhere = strWhere & "([EnrNo] = """ & Me.txtFilter & """) OR "
strWhere = strWhere & "([FirstName] = """ & Me.txtFilter & """) AND "
End If
'Date field example. Use the format string to add the # delimiters and get the right international format.
If Not IsNull(Me.txtFrom) Then
strWhere = strWhere & "([RegDate] >= " & Format(Me.txtFrom, conJetDate) & ") AND "
End If
'Another date field example. Use "less than the next day" since this field has times as well as dates.
If Not IsNull(Me.txtTo) Then 'Less than the next day.
strWhere = strWhere & "[RegDate] BETWEEN #" & Format(Me.txtFrom, "mm/dd/yyyy") & "# AND #" & Format(Me.txtTo, "mm/dd/yyyy") & "# "
End If
lngLen = Len(strWhere) - 5
If lngLen <= 0 Then 'Nah: there was nothing in the string.
MsgBox "No criteria", vbInformation, "Nothing to do."
Else 'Yep: there is something there, so remove the " AND " at the end.
strWhere = Left$(strWhere, lngLen)
'Debug.Print strWhere
Me.Filter = strWhere
Me.FilterOn = True
End If
End Sub
It displays “Run-time error ‘3075’: Syntax error in data in query expression ‘([EnrNo] = “MS-12/IT-004”) or ([FirstName] = “MS-12/IT-004”) AND ([RegDate] >= #06/16/2014#) AND [RegDate] BETWEEN #06/16/2014# AND #09/23/2’ you have too many operands here.
You will need to make it so your query's where statement is as follows;
(([EnrNo] = “MS-12/IT-004”) or ([FirstName] = “MS-12/IT-004”)) AND (([RegDate] >= #06/16/2014#) AND ([RegDate] BETWEEN #06/16/2014# AND #09/23/2014#))
Note the extra brackets I have placed in there. Logical operators (OR/AND) will return a value based upon TWO expressions. So for instance, a > b AND b > c returns true if BOTH conditions are true. a > b OR b > c returns true if EITHER statement is true.
If we write a statement like a > b and b > c or d > f we have too many conditions, so we need to nest them. So we would write it as (a > b AND b > c) OR d > f.
A good way to practice this is to create the query with the criteria manually in the query builder, then look at the bracketing placed on your conditions in the SQL view window of the query.
I hope this helps!

Fill Field When All Checkboxes Toggled Access 2010

I have an expenditures subform in Access 2010 that lists the predicted costs associated with the project for each year. Most projects only have one year, but some have more than one. Each cost has a Final checkbox next to it that should be checked when the amount is confirmed, ie. at the end of each year.
It basically looks something like this:
Year | Cost | Final
--------+-----------+--------------------
2017 | $100 | [checked box]
2018 | $200 | [unchecked box]
| | [unchecked box]
I have another field outside the table, FinalCost, that adds up everything in the Cost field. Right now, it fills in the amount from any year which has a checked Final box. That should only be filled when all the Final boxes are checked.
Ex. Right now, it should show nothing even though Final for 2017 is checked. When 2018 is checked, it should show $300. Instead, it shows $100 even though there's still an empty checkbox.
This is the code for this form.
Private Sub Form_AfterUpdate()
Dim rs1, rs2 As Recordset
Dim sql, sql2 As String
sql = "SELECT Sum(Amount) as Final From Expenditures " & _
"Where ProjNo = '" + Me.ProjNo + "' And Final = True Group by ProjNo"
sql2 = "SELECT FinalExpenditure From ActivityCash " & _
"Where ProjNo = '" + Me.ProjNo + "'"
Set rs1 = CurrentDb.OpenRecordset(sql, dbOpenDynaset, dpinconsistent)
Set rs2 = CurrentDb.OpenRecordset(sql2, dbOpenDynaset, dpinconsistent)
If rs1.RecordCount > 0 Then
If rs2.RecordCount > 0 Then
Do While Not rs2.EOF
rs2.Edit
rs2!FinalExpenditure = rs1!Final
rs2.Update
rs2.MoveNext
Loop
End If
End If
rs2.Close
rs1.Close
Set rs1 = Nothing
Set rs2 = Nothing
End Sub
What would be the best way to go about doing this?
EDIT: When the last box is checked, a new row is automatically added with an untoggled checkbox but no information.
Replace the statement beginning with sql = ... with this:
sql = "SELECT SUM(e1.Amount) AS Final " & _
" FROM Expenditures AS e1 " & _
" WHERE NOT EXISTS (SELECT 'x' FROM Expenditures e2 WHERE e2.Final=0 AND e1.ProjNo = e2.ProjNo) " & _
" AND e1.ProjNo = '" & Me.ProjNo & "'"
This query will return data only if there are all expeditures for the project marked as final. As you check for rs1.RecordCount > 0 there will be no update if this query returns no records.
So, before sql, I would verify that all records have True in your Final field.
To do that, let's just return a COUNT() of (any) records that have Final = False, and we can then decide to do what we want.
So, something like,
Dim Test as Integer
test = DCount("*", "YourTableName", "Final = False AND ProjNo = " & Me.ProjNo &"")
If test > 0 Then
'Don't fill the box
Else
'Fill the box, everything is True
'Read through your recordsets or whatever else you need to do
End If
To use a query, we essentially need to replicate the Dcount() functionality.
To do this, we need another Recordset variable, and we need to check the value of the Count() field from our query.
Create a query that mimicks this:
SELECT COUNT(*) As CountTest
FROM YourTable
HAVING Final = False
AND ProjNo = whateverprojectnumberyou'reusing
Save it, and remember that query's name.
Much like the DCount(), we need to make this "check" determine the route of your code.
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("YourQuery'sNameHere")
If rst!CountTest > 0 Then
'They are not all Checked (aka True)
Else
'Supply the value to the FinalCost
End If
Set rst = Nothing
Change this:
sql = "SELECT Sum(Amount) as Final From Expenditures " & _
"Where ProjNo = '" + Me.ProjNo + "' And Final = True Group by ProjNo"
For this:
"SELECT SUM(Amount) - SUM(IIF(Final,1,0)*Amount) as YetToConfirm, SUM(Amount) as Confirmed From Expenditures " & _
"Where ProjNo = '" + Me.ProjNo + "' Group by ProjNo"
rs1 will return two values, the total value if all costs were confirmed in the rs1!Confirmed, and the value yet to confirm in rs1!YetToConfirm
Then here:
Do While Not rs2.EOF
rs2.Edit
rs2!FinalExpenditure = rs1!Final
rs2.Update
rs2.MoveNext
Loop
change it to:
Do While Not rs2.EOF
rs2.Edit
rs2!FinalExpenditure = Iif(rs1!YetToConfirm = 0, rs1!Confirmed, 0)
rs2.Update
rs2.MoveNext
Loop
One way to process this would be check using a subquery whether last year(verified using a dmax function) in each project has been checked in the final column, if this is true, get your sum of checked amounts, else dont calculate the sum.
I have modified your sql string to include this and I tested it against your given example to confirm its showing a sum of $300 or nothing.
SQL = ""
SQL = SQL & " SELECT Sum(Amount) as Final From Expenditures "
SQL = SQL & " Where ProjNo = '" & Me.ProjNo & "' And Final = True "
SQL = SQL & " And (SELECT Expenditures.Final FROM Expenditures where year = ( "
SQL = SQL & " DMax('Year','Expenditures','ProjNo= " & Chr(34) & Me.ProjNo & Chr(34) & "'))) = true "
SQL = SQL & " Group by ProjNo "

Moving Dates to Access Table Fields - Incorrect Dates Printed

I'm having some issues with moving the CurrentDate and LastDayOfMonth to a table in Access for data processing
Dim CD As Date
Dim LDOM As Date
CD = DateSerial(Year(Date), Month(Date), Day(Date))
'Format(Now(), "mm-dd-yyyy")
LDOM = DateSerial(Year(Date), Month(Date) + 1, 0)
'Add Dates
CurrentDb.Execute "UPDATE tblProcess " & _
"SET tblProcess.[CurrentDate] = " & CD
CurrentDb.Execute "UPDATE tblProcess " & _
"SET tblProcess.[DueDate] = " & LDOM
Debug.Print CD
Debug.Print LDOM
Everytime I Debug.Print - either the formula or the variable - it ALWAYS comes out correct.
But what ends up on my table for both fields is "12/30/1899" Can anyone help?
Test simply:
CurrentDb.Execute "UPDATE tblProcess" _
& " SET tblProcess.[CurrentDate] = #" & Format(CD, "yyyy-mm-dd") & "#;"
Your original code uses SQL like this:
UPDATE tblProcess SET tblProcess.[CurrentDate] = 12/03/2013
that is BAD for Access DATETIME field.
Instead we need in final for Accesss SQL string:
UPDATE tblProcess SET tblProcess.[CurrentDate] = #2013-12-03 22:00:13#;
Please stop voting up for such a small contribution, I have not said the last word, for SQL Server, we must use:
UPDATE tblProcess SET CurrentDate = '2013-12-03T22:00:13';
Although Access and SQL Server are both Microsoft of Bill Gates.

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