Reference table and form text box MS Access VBA - vba

Pardon the code below. I am a VBA novice. I am looking to upon clicking a form button, inform customers that they must make another library selection if the item they have chosen is checked out. I determine something is checked out if the "Check In Date" for the most recent date in the "1Transaction" table is NULL. Note for every check in and check out, a new record is created in the 1Transaction table and every record (whether check in or check out) will have the check out date info. So the logic, take the most recent date for the lease (book) number and if there is no return date then it is still checked out. The code below is meant to make the references and return a message box in VBA but I am stuck. I understand logically what I require but I know my VBA syntax is very off. Thanks.
Private Sub Check_Out()
If [1Transactions].[Asset].Value = Me.Lease_Num
And DMax([Tables]![1Transactions].[Check Out Date])
And [Tables]![1Transactions].[Check In Date] = NULL
Then MsgBox "The requested documents are currently checked out"
End If
DoCmd.OpenForm "Check In"
End Sub
Note:
1Transactions = Table holding all check in/out data
Me.Lease_Num = value pulled from combo box that user fills out to provide "lease number" (book code) they are interested in checking out.

Okay - instead of trying to modify every line of your code, I think it's better to use a Parameter Query to simple check if the item is out now
First create a query using your transactions table - modify the SQL to below
and save it as "qdfLease"
PARAMETERS [What Lease Num] Text ( 255 ); SELECT TOP 1
[1Transactions].Asset, [1Transactions].[Check Out Date],
[1Transactions].[Check In Date] FROM 1Transactions WHERE
([1Transactions].Asset = [What Lease Num]) And ([1Transactions].[Check
In Date] Is Null) ORDER BY [1Transactions].[Check Out Date] DESC;
Modify the code in your sub to:
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strLeaseNum As String
strLeaseNum = nz(Me.Lease_Num,"")
Set qdfLease = CurrentDb.QueryDefs("qdfLease")
qdfLease.Parameters("What Lease Num") = strLeaseNum
Set rs = qdfLease.OpenRecordset(dbOpenDynaset, dbReadOnly)
If rs.EOF Then
' Item is Checked In
Else
' Item is Checked Out
End If
rs.Close
Set rs = Nothing

You have [1Transactions].[Check Out Date].Value = Me.Lease_Num
Is that what you want to compare the lease_num to? It sounds like it should be a different field name in [1Transactions]
I would change this
[Tables]![1Transactions].[Check In Date] = NULL
to this
IsNull([Tables]![1Transactions].[Check In Date])
What are you trying to compare here
DMax([Tables]![1Transactions].[Check Out Date])

Related

Access Form checkbox to update date in another table

I'm trying to make a form checkbox update a date in another table.
Private Sub Delivered_AfterUpdate()
If Delivered = -1 Then
[tool implentation].[date] = Now()
End Sub
I'm getting an error on the [tool implentation].[date] = Now() line.
I would like if any time the checkbox is clicked (check and un-check) the date is updated.
I'm assuming your table is also the form's recordset here. If it is not you will need something to determine which record in the table you want to edit.
Private Sub Delivered_AfterUpdate()
If Me.Delivered = True Then
With Me.Recordset
.Edit
![ImplementationDate] = Now()
.Update
End With
End If
End Sub
You can leave Me.Delivered = -1 if you want but I find True/False to be easier to read.
I also recommend not naming something Date, I'm not sure if it actually matters as a column name, but it is both a builtin function and data type. So I changed it.
You should also indent your code, it will be a nightmare as you get more lines.

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

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, ...

MoveFirst works on first call, fails on second

I am creating an Access 2007 database, which contains two tables (Applicants and Opportunities) and a link table (Applicants-Opportunities). I am populating these tables from a flat file in another table using VBA. The code for checking whether a record already exists in the link table is
szSQL = "((([Applicants-Opportunities].[User Id])="""
& rsInc![User Id] & """)
AND (([Applicants-Opportunities].[Opportunity Id])="""
& rsInc![Opportunity Id] & """))""
rsLnk.FindFirst szSQL
The first time through, with all three tables blank, this code works. The second time, I get a 3070 error saying that the system doesn't recognise "Applicants-Opportunities.User Id" as a valid field name.
I'm at a complete loss. If it worked the first time, why not the second? Neither Id in the second case is the same as in the first.
.FindFirst method change current position to first found record and change property .NoMatch to False. If nothing found .NoMatch is true.
If you need search another records you can use .FindNext method with checking .NoMatch property.
You can read about in manual from msdn. There is example.
But, you might use sql for your target. Something like this:
UPDATE [Applicants-Opportunities] INNER JOIN [another table]
ON [Applicants-Opportunities].[User Id] = [another table].[User Id]
AND [Applicants-Opportunities].[Opportunity Id] = [another table].[Opportunity Id]
SET [Applicants-Opportunities].[SomeField] = 'SomeValue'
WHERE [Applicants-Opportunities].[SomeOtherField] = 'SomeOtherValue'
sorry for my english)

Checking for date overlap across multiple date range objects

I have several records in a database that have Start and End Dates
09/15/2011 - 09/30/2011
10/15/2011 - 10/22/2011
11/01/2011 - 11/15/2011
When user stores a record, I need to make sure dates don't overlap.
My simple code checks date ranges within a specific record (e.g. user enters 9/16/2011 or 10/21/2011, I throw an exception.)
But, on the slim chance a user gets creative (e.g. 10/14/2011 - 10/23/2011 or even 10/14/2011 to 11/16/2011), now they have circumvented my check.
BTW, the user could enter 10/14/2011 to 10/23/2011 if they were editing the record that contained values 10/15/2011 - 10/22/2011.
So, I'm trying to solve this riddle with a linq query. However, what I have isn't working exactly right.
UPDATE Nevermind about code not working. While trying to provide an example to expand on Miika's repsonse, I found my answer. So, giving credit to Miika for pointing me in the right direction and posting my working code below:
Here's my code:
Private Sub CheckForOverlap(myMonth As Messages.MyMonth)
Dim am As New MyMonth()
Dim amCollection As Messages.MyMonthCollection
Dim overlappingMyMonthDate As Boolean = False
Dim sErrorMsg As String = ""
'...non-applicable code omitted
Dim query = From s In amCollection _
Let s1 As MyMonth = CType(s, MyMonth) _
Where s1.AttendanceMonthID <> attendanceMonth.AttendanceMonthID And _
(CDate(attendanceMonth.StartDate) < CDate(s1.StartDate) And CDate(attendanceMonth.EndDate) > CDate(s1.EndDate)) _
Select s1
If query.Count > 0 Then
sErrorMsg = "Dates entered surround another entry"
End If
If overlappingMyMonthDate Then
Throw New Exception(sErrorMsg)
End If
End Sub
End Class
It all came down a LINQ query.
Do you need to do it in code or would SQL be an option? If the data is in a database, you could use the following query to check for overlaps.
SELECT COUNT(*)
FROM Table1
WHERE Table1.StartDate < 'endCheckDate'
AND Table1.EndDate > 'startCheckDate'
This will return a count of the number of overlaps found. 'endCheckDate' and 'startCheckDate' are your new query values (in date format). If your data is in a object collection in memory, then you could use LINQ. If you need help with a LINQ statement, let me know.

Creating Recordset with SQL statement

I am trying to create a recordset in Access VBA that will show me all records in a table related to the current record of a form. My current code looks like this:
Private Sub Form_Load()
Dim rst As Recordset
Set rst = CurrentDb.OpenRecordset("Select [ID], [Ln] From [Order Detail] Where ((([Order Detail].[ID]) = [Forms]![Order Data Entry Header]![ID]))")
rst.MoveLast
Forms![Order Data Entry Header].LineNum = rst![Ln]
End Sub
I am doing this so that when adding new records they can be numbered sequentially after the highest number. When I run the form it get "Run-time Error: '3061' Too few parameters. Expected 1." on the Set rst line.
Any help would be appreciated.
The issue is the fact that the string you see there is exactly what is getting passed to the driver.
You need to "build up" the string, like so:
Set rst = CurrentDb.OpenRecordset("Select [ID], [Ln] From [Order Detail] Where ((([Order Detail].[ID]) = " & [Forms]![Order Data Entry Header]![ID] & "))")
Watch to make sure that [Forms]![Order Data Entry Header]![ID] is safe content, since you are building up an SQL statement.