MS Access VBA - Custom Column is ListBox (using a value from another column coming from a table) - sql

Hello Stackoverflow community!
My question is in reguards to creating a custom column within a list box that is pulling from a table using SQL. Refering to the code and picture of the current list below, I want to create a custom column that is not stored in a table, that will be called "DaysActive" and will take todays date minus the StatusEffect Date for each individual record displayed and give the number of days in its own column, say between StatusEffect and Yr. Is this possible? Thank you in advance for taking the time to read through this.
Private Sub Form_Load()
DoCmd.RunCommand acCmdWindowHide
Dim rs As Recordset
Dim strSQL As String
Dim lstnum
strSQL = "SELECT LastName, FirstName, Status, StatusEffect, Yr, Make, Model, VIN, Deduction, USLicense, RegistrationState, Dependents,Notes, ID FROM InsuranceTable" & _
"WHERE SentRegistration = False And Status IN ('active','add') Order By StatusEffect Desc "
Set rs = CurrentDb.OpenRecordset(strSQL, dbOpenSnapshot)
Set Me.lstInfo.Recordset = rs
lstnum = [lstInfo].[ListCount]
Me.lstcount.Value = lstnum - 1
End Sub
Link to picture of my current list since I do not have enough rep points to embed it ;/

Use the DateDiff() function in your SQL.
DateDiff('d') returns the difference in days.
SELECT ..., StatusEffect, DateDiff('d',[StatusEffect],Date()) AS DaysActive, Yr, ...

Related

Access subtract form value from another query

In MS Access using VBA trying to subtract a calculated value (time between dates) from a total amount of time in another table.
The query holding the total amount of time is QryScsBatchHandler the field I want to subtract the value from is FreezerLifeUsed and the match condtion is BatchID
The query holding the value I want to subtract is QrySCSMaterialFreezerLog or the form is Frm_MaterialFreezerLog.. the value is AccumilatedTime and the Match condition is Batch ID
Private Sub BkInFrzr_Click()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb()
strSQL = "SELECT FreezerLifeUsed FROM QryScsBatchHandler WHERE [BatchID] = BatchID"
Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
With rst
.MoveFirst
.Edit
FreezerLifeUsed = -AccumilatedTime
.Update
End With
End Sub
I can’t seem to get this simple subtraction to work… any suggestions on what’s not right?
Any help will be greatly appreciated..
At least 3 issues with code.
concatenate reference to form field/control for dynamic criteria in SQL:
strSQL = "SELECT FreezerLifeUsed FROM QryScsBatchHandler WHERE [BatchID] = " & Me.BatchID
The VBA needs to use dot or bang when referencing controls or fields and qualifying with prefix is advised:
!FreezerLifeUsed
Me.AccumilatedTime
Nothing is subtracted from anything, so consider:
!FreezerLifeUsed = !FreezerLifeUsed - Me.AccumilatedTime
However, if query is expected to return only one record, don't bother with loop. Also, instead of opening a recordset, an UPDATE action would work.

In MS Access, is it possible to add an updatable blank field to a query to calculate it's values programmatically in VBA?

In MS Access, in order to prevent nesting queries, because it has become really slow, I'm trying to calculate programmatically in VBA all calculated fields for my queries using a Loop. In general, the idea is to stop using calculated fields on queries at all, to perform all calculations from the backend.
I am having problems showing the values in a TextBox in a Continuous Form. I'm trying to create a query in VBA with an empty field and then update the field with the calculated values, so then I can set the ControlSource of the textbox to that field for it to show properly. The problem is that since the empty field is a calculated field, I cannot update it's value. Is there any other way to add a field to a query that remains empty and updatable until I can calculate it's values?
An alternative solution would be to create a temporal table instead of a query and update the values, but I would really prefer not to create temporal tables every time an user needs to do a query with calculated fields (especially nested ones).
Is there a way to accomplish this?
Here is what I tried:
Private Sub Form_Load()
Dim SQLQ As string
Dim rs As DAO.Recordset
Dim dbs As DAO.Database
Dim qrydef As DAO.QueryDef
Dim i As Integer
'calcField1 is not a member of Items, and it's intended to be updated later on
SQLQ = "SELECT Items.Price, calcField1 FROM Items;"
Set dbs = CurrentDb()
Set qrydef = dbs.CreateQueryDef("testqry", SQLQ)
'Field is prompted for a value when the query is called and has no source
qrydef!calcField1 = vbNullString
Set rs = qrydef.OpenRecordset()
i = 0
Do Until rs.EOF
rs.Edit
rs!calcField1 = rs!Price *2 'Error here because calcField1 is a Calculated Field
rs.Update
i = i + 1
rs.MoveNext
Loop
Me.TextBox1.ControlSource = "=Price"
Me.TextBox2.ControlSource = "=calcField1"
Set Me.Recordset = rs
Me.Refresh
End Sub
I think it is better to create another table where you can insert the new calculated record with a reference to the original table so they are linked.
for example:
table 1:
item_id, item_desc, price
table 2:
item_id, calculated_value
then, the calculated value can be inserted or modified depending on the purpose of your calculation process.
Can you add the calculated field into a query and use that as the Record Source?
Private Sub Form_Load()
Dim strSQL As string
'calcField1 is calculated
strSQL = "SELECT Items.Price, (Items.Price * 2) AS calcField1 FROM Items;"
Me.TextBox1.ControlSource = "=Price"
Me.TextBox2.ControlSource = "=calcField1"
Set Me.RecordSource = SQLQ
Me.Refresh
End Sub
or if the logic is more complex you can put it into a function
'in the form
Private Sub Form_Load()
Dim strSQL As string
'calcField1 is computed by a function
strSQL = "SELECT Items.Price, MyFunction(Items.Price) AS calcField1 FROM Items;"
Me.TextBox1.ControlSource = "=Price"
Me.TextBox2.ControlSource = "=calcField1"
Set Me.RecordSource = strSQL
Me.Refresh
End Sub
'in a module
Public Function MyFunction(dbl As Double) As Double
MyFunction = dbl * 2
End Function

VBA MS Access Getting the start date in a database

I have a MS Access database and inside it I import tables from an external source every month. What I want to do is get the earliest date in the database since it is out of order. I am creating forms and so far this is what I have:
'Get start and end date
Dim DBGeo As DAO.Database
Dim rstStartDate As DAO.Recordset
Set DBGeo = CurrentDb
varStartDate = "SELECT [time] FROM [" & cboTableName & "] ORDER BY [time] ASC LIMIT 1;"
MsgBox (varStartDate)
Set rstStartDate = DBGeo.OpenRecordset(varStartDate, dbOpenSnapshot)
The field name is called time and I know that is a keyword but I dont want to change it or else I have to change it in all the tables. CboTableName has the name of the table I am using.
Im not great at this stuff so I am sure it is something simple. Thank you
SELECT TOP 1 Table1.Time
FROM Table1
ORDER BY Table1.Time;

Why is the value extracted from database not showing what is intended?

I have the following SQL Statement:
SELECT StockChild.ProductId, Sum(StockChild.Qty) AS SumOfQty,
PRODUCTDETAILS.Title, Sum(SALESORDERchild.Stockout) AS SumOfStockout
FROM (PRODUCTDETAILS
INNER JOIN SALESORDERchild
ON PRODUCTDETAILS.productID = SALESORDERchild.ProductId)
INNER JOIN StockChild
ON PRODUCTDETAILS.productID = StockChild.ProductID
WHERE (((StockChild.ProductID)=[Forms]![StockChild]![ProductId])
AND ((SALESORDERchild.ProductID)=[Forms]![StockChild]![ProductId]))
GROUP BY StockChild.ProductId, PRODUCTDETAILS.Title;
I'm trying to get the summation of values from 2 different tables using the above SQL Statement in access:
1) Sum of StockChild quantity based on productID
2) Sum of Salesorderchild Stockout based on productID
If i query it separately, i managed to get the values that i needed but i'm unable to put it into a single form.
but when i query it together as above, the values jump all over the place and i can't seem to understand why.
And if i add another record in the salesorderchild, of the already existing isbn, all the values will jump as well.
is there something that i am doing wrongly? or how should i go about to tackle this matter.
I added some explanations in the image attached.
Update:
I was trying another method whereby i just did a normal query for the initial stock to be displayed(which worked fine getting the numbers i need)
and over in the Total stockout i was trying out a
=DSum("[stockout]","[SALESORDERchild]","[ProductId]=" & [Forms]!
[StockChild]![ProductId])
but it was returning me a #Name? did i use this correctly?, should i do a vba code instead or is there a way to do it this way?
i tried the following vba code function as an alternative to select out the value but it was telling me the user-defined type not defined. am i missing out something? - (fixed this part by defining the reference of active x data object)
Private Sub Form_Current()
Dim intI As Integer
Dim fld As Field
Dim rst As ADODB.Recordset
Dim pid As String
pid = ProductID.Value
Set rst = New ADODB.Recordset
rst.Open "SELECT Sum(SALESORDERchild.Stockout) AS SumOfStockout FROM
SALESORDERchild WHERE SALESORDERchild.ProductID ='" & pid & "';",
CurrentProject.Connection, adOpenKeyset, adLockOptimistic
tb_stockout.Value = rst.Fields("SumOfStockout")
End Sub
Done Thanks everyone :)

How to use a query as a control source for a textbox on a form?

I have a form myForm that's binded to a table tbl in my database. (I don't know if binded is the correct term, but It shows records from tbl on by one.)
In the form:
contact: textbox, binded to tbl.contact.
dailyCount: textbox, should show the amount of contacts entered today.
In the table:
contact
dateEntry
The query I want to use is:
SELECT count(*)
FROM tbl
WHERE contact = currentContact
AND month(dateEntry) = month(now)
AND day(dateEntry) = day(now)
AND ear (dateEntry) = year(now)
Where currentContact is the contact that is showing on the form now.
I tried putting the query in the dailyCount dataSource, but It's not working. When I click on the three dots on datasource to access the wizard, I get a window to build functions and not queries.
How do I get the currentContact showing on the form into the query?
There are multiple ways to do this. For a couple of reasons, I don't like to hardcode queries in the datasource of a specific field, and I mostly build/assign all my queries in VBA. So here's how I would do it.
In the load event of you form :
Private Sub Form_Load()
Dim SQL As String
Dim RST As Recordset
dim theCOntact as string ' Change accordingly
theCOntact = Me.currentContact ' I don't know how your fields are named, so change accordingly
SQL = "SELECT count(*) AS cnt FROM tbl WHERE contact = " & theContact & "' AND month(dateEntry) = month(now) AND day(dateEntry) = day(now) AND Year(dateEntry) = year(now)"
Set RST = CurrentDb.OpenRecordset(RST)
If RST.BOF Then
dailyCount.Value = RST!cnt
Else
dailyCount.Value = 0
End If
End Sub
Assuming your contact field is string, if its a number remove the quotes in the SQL
Probably the simplest approach is to use the DLookup function with an associated query:
Create and save a named query with your SQL code or equivalent. Let's call it "qryDailyCount". Note that it should be modified to look something like this (in particular, name the column and change the record reference to a GROUP BY for now):
SELECT count(*) as DailyCount
FROM tbl
WHERE month(dateEntry) = month(now)
AND day(dateEntry) = day(now)
AND year (dateEntry) = year(now)
GROUP BY contact
In the dailyCount textbox, set the Control Source to something like this:
=DLookUp("Count";"qryDailyCount";"contact = [contact]")
(Note that if the contact field is a text field, you must enclose it with single quotes.)