MS Access 2016. Synchronize two combo boxes on a form datasheet - ms-access

I have two cascading lookup table comboboxes on a Datasheet form.(SessionCategories - SessionTypes). I'm having the following problems:
1) When the form loads I only see the values from the SessionTypes that correspond to the first SessionCategories ID.
2) When I change a value on the SessionCategories combo, all the SessionTypes values change across the datasheet and not only the selected.
Any ideas? Do I need to include something on the Form Load? More info and a couple of different approaches below.
Thanks.
ATHLETE_SESSION table
sessionOverviewID
sessionTypeID
SESSION_CATEGORIES
sessionOverviewID sessionOverview
1 aerobic
2 anaerobic
SESSION_TYPE
sessionTypeID sessionType sessionOverviewID
1 anaerobic1 2
2 anaerobic2 2
3 anaerobic3 2
4 aerobic1 1
5 aerobic2 1
6 aerobic3 1
sessionCategoriesID lookup properties:
Display control: Combo Box
Row Source Type: Table/Query
Row Source: SessionCategories
Bound Column: 1
Column Count: 2
Column Widths: 0cm;2cm
sessionTypeID lookup properties:
Display control: Combo Box
Row Source Type: Table/Query
Row Source:
Bound Column: 1
Column Count: 2
Column Widths: 0cm;2cm
1st approach:
Private Sub comboSessionCategories_AfterUpdate()
Dim strSQL As String
strSQL = "SELECT SessionType.sessionTypeID, SessionType.sessionType FROM SessionType WHERE (((SessionType.sessionOverviewID)=" & [Forms]![Session]![comboSessionOverview] & "))"
Me.comboSessionType.RowSource = strSQL
End Sub
2nd approach:
Private Sub comboSessionCategories_AfterUpdate()
Me.comboSessionType.RowSource = "SELECT SessionType.sessionTypeID, SessionType.sessionType" & _
" FROM SessionType WHERE SessionType.sessionOverviewID=" & Me.comboSessionOverview
Me.comboSessionType = Me.comboSessionType.ItemData(0)
End Sub

Related

Obtaining non duplicate values from Access listbox column

In Access 2016 I have a multi-select listbox with a single column :-
Item 1
Item 1
Item 2
item 3
Item 3
In VBA, is there a way that I can remove duplicates from selected rows and display the remaining values in a message box. So, the following values would be displayed from the data above (assuming all rows are selected) :-
Item 1
Item 2
item 3
Use a dictionary and check for duplicates before adding new item
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
For lngRow = 0 To ListBox.ListCount - 1
If .Selected(lngRow) Then
If Not dict.exists(ListBox.Column(0, lngRow)) Then
x.Add ListBox.Column(0, lngRow), ""
End If
Next
For Each x In dict.keys
Str = Str & x & vbNewLine
Next
MsgBox Str

Access 2013 - sequential numbering without autonumber

New to this site and access.
I am trying to create a database to keep track of a master log. Need help with sequential numbering. I currently have the following tables.
PO Table
POID - Autonumber(PK)
PODate - Date/Time
Supplier - String
Item Table
ItemID - Autonumber(PK)
POID - Ingeter(FK)
ItemDescription - String
Quantity - Integer
MasterLog Table
MasterLogID - Autonumber(PK)
ItemID - Integer(FK)
PieceNumber - Integer ( 1,2,3 ... etc)
MFG - String
Process - String
Length - Integer
MfgIDNum - String (ABD123XTY-1234)
I am trying to automate the data entry of the PieceNumber field. So when you enter a new PO and add items to it, once received. It will add a row to the masterlog table starting at piece number 1 through how ever many pieces we have. We number the pieces based on the items we purchased.(i.e. with Item 1 we purchased 100 pieces. So I would have Item 1 piece 1 through 100.) Then we are able to add the other data to the table. Just trying to reduce some data entry time and avoid some mistakes in the numbering of this field.
Any ideas?
Something like this would be a very simple way of doing it. You'd have to have a predefined table called Numbers with integers starting from 1 to however high a quantity you might have:
INSERT INTO MasterLog (ItemID, PieceNumber)
SELECT Item.ItemID, Numbers.Number
FROM Item, Numbers
WHERE (Item.ItemID = Forms!Items!ItemID) AND
(Numbers.Number <= Item.Quantity)
ORDER BY Numbers.Number
If you wanted to add the pieces one by one you could default the PieceNumber field on the related form. Make sure you default MasterLog.ItemID as well:
=Nz(DMax("[PieceNumber]","[MasterLog]","[ItemID] = " & Forms!Items!ItemID), 0) + 1
For a VBA solution try something like this:
Dim db As Database
Dim strSQL As String
Dim frm As Form
Dim i As Integer
Set db = CodeDb()
Set frm = Forms!Items
If frm!Quantity > 0 Then
For i = 1 To frm!Quantity
strSQL = "INSERT INTO MasterLog (ItemID, PieceNumber) " & _
"SELECT " & frm!Item & " AS ItemID, " & _
i & " AS PieceNumber"
db.Execute strSQL, dbFailOnError
Next i
End If
Set db = Nothing
All of these presume a form displaying your current item called Items.

excel vba - add table column with date based on adjacent cell that includes date and time

I have an excel table ("Table1") with 4 total columns. The 3rd and 4th column contain 'clock in' and 'clock out' information formatted to show date and time. For example :
6/3/2016 10:54:52 AM
I would like to do two things here...first, I want to create a new, 3rd column that just reads the date, formatted "d-mmm". This should match the date found in what would now be column 4.
The second thing I would like to do is take the date portion of text out of what would now be columns 4 and 5. So at the end, an example row of data might read as follows (columns 3:5):
C, D, E
7-Jun, 10:54:52 AM, 4:59:44 AM
Here is what I have so far for code:
Sub test()
Dim currentSht As Worksheet
Dim lst As ListObject
Set curretnSht = ActiveWorkbook.Sheets(1)
Set lst = currentSht.ListObjects("Table1")
lst.ListColumns.Add Position:=3
'Not really sure how to do the rest
End Sub
That's not the Excel way. Dates are numbers 0 represents 1/1/1900. Add 1 to it and you get the next day the value of an hour is 1/24 .
The biggest problem of your approach is Excel you stop editing the cell Excel evaluate the cells value. It'll still look like 7 - Jun but Excel changes the cells format and the cells value to be 7 - Jun of this your 6/7/216. It's best to have all the cells equal the same date. Just change the cells formatting to display the results that you want. If you need to calculate the Month use the a WorkSheet Function to do so. =Month(A1)
Try this:
Sub Demo()
Range("C1").EntireColumn.Insert '-->insert column
Range("D:D").Copy Destination:=Range("C1") '-->copy column 4 to column 3
Range("C:C").NumberFormat = "d-mmm" '-->format column 3
Range("D:E").NumberFormat = "h:mm:ss AM/PM" '-->format column 4 and 5
End Sub
Even this will work:
Sub Demo()
Dim currentSht As Worksheet
Dim lastRow As Long
Set currentSht = ActiveWorkbook.Sheets("Sheet1")
lastRow = currentSht.Cells(Rows.Count, "C").End(xlUp).Row '-->get last row with data
currentSht.Range("C1").EntireColumn.Insert '-->insert column
currentSht.Range("C1:C" & lastRow) = currentSht.Range("D1:D" & lastRow).Value '-->copy column 4 to column 3
currentSht.Range("C1:C" & lastRow).NumberFormat = "d-mmm" '-->format column 3
currentSht.Range("D1:E" & lastRow).NumberFormat = "h:mm:ss AM/PM" '-->format column 4 and 5
End Sub
This meets your specs:
Sub InsertColumnAndFormatDates()
Columns("C:C").Copy
Selection.Insert Shift:=xlToRight
Application.CutCopyMode = False
Columns("C").NumberFormat = "d-mmm"
Columns("D:E").NumberFormat = "h:mm:ss AM/PM"
End Sub

Filtering Data from a specific column

Hello Everyone I am at a dilemma I am trying to find out a way to filter out certain data in a column field I have an idea on how to do this but I do not know the correct syntax to use. First here is the table and here is the code structure I would like to write.
for i=1 to length of column First Match
for j=1 to length of column Second Match
If ((value of the data in column First Match = 15) OR (value of the data in column FirstMatch = 1)) AND
((value of the data in column Second Match = 15) OR (value of the data in column Second Match = 1))
Then
Filter the data and append so the filtered datas are saved for both First Match and Second Match
end if
next
next
I am trying to filter out the data that is a 15 and 1 so that only data that have the values 0,2,3,4,5,6...14 will be shown for instance the information of john and steve will not be shown because both the first and second match fields have a 1 or 15 but the rest of data will be shown my form is a split form setup.
Is my method correct?
First Name Last Name First Match Second Match
James Matheson 0 2
Monroe Labonson 4 3
Barack Obama 2 5
Frederick Douglas 3 4
Steve MCGowan 1 1
John Seals 15 15
Mike Omalley 14 15
Set rs = CurrentDb.OpenRecordset("Table1")
Do While Not rs.EOF
If rs!Fields("First Match") > 1 And rs!Fields("First Match") < 15 And rs!Fields("Second Match") > 1 And rs!Fields("Second Match") < 15 Then
End If
Loop
With a better understanding (I hope) I've reproduced your data in Access and built a query that does what you seem to ask. The best way to see this is to create a new query, not add a table, and go directly to SQL view. Paste the following SQL statement (the one in quotes) in and replace matchFilter with your table name.
In your event code you can create a recordset based on the SQL:
Dim sSQL as string, rs as Recordset
sSQL = "SELECT matchFilter.[First Name], matchFilter.[Last Name], matchFilter.[First Match], matchFilter.[Second Match] " & _
"FROM matchFilter " & _
"WHERE ((([First Match]<>1 And [First Match]<>15 And [Second Match]<>1 And [Second Match]<>15)=True))"
Set rs = CurrentDB.OpenRecordset(sSQL)
' now do what you want
Wrong answer below!
Dim rs as Recordset
Set rs = CurrentDB.OpenRecordset("yourTableName")
Do While Not rs.EOF
If rs!Fields("col1") > 1 AND rs!Fields("col1") < 15 AND rs!Fields("col2") > 1 AND rs!Fields("col2") Then
'do what you have to do with filtered out records
End If
Loop
I have found the solution apparently it was just a misunderstanding because the first time I tried this code I thought it was wrong but it was because my field names did not have spaces in between the first time I wrote them.
Me.Filter = ""
Me.Filter = "[First Nam]<>'Jamie' AND [Last Nam]<>'Cartman'"
Me.FilterOn = True

building a search form in Access 2010

I am trying to make search customer form for access 2010.
I like to have an option group based on a query search. I made a search query looking for first name or last name. two textboxes are also present on the form to fill up the query inputs (1st and last name)
I need option group so that I can select the resulted name for booking purposes.
In the past I have made an indirect way of doing this using subform and a checkbox.
Then loading both results on a subform and checkbox (requery) so the user only has to select on the checkbox. But this time I want the options to be the query result itself! Please help.
Here is a simple example that uses a List Box:
Table: Clients
ID - AutoNumber
LastName - Text(255)
FirstName - Text(255)
Email - Text(255)
Test data:
ID LastName FirstName Email
-- ---------- -------------- ------------------
1 Thompson Gord gord#example.com
2 Loblaw Bob bob#example.com
3 Kingsley Hank hank#example.com
4 Thompson Hunter S. hunter#example.com
5 Squarepants Spongebob ss#example.com
6 O'Rourke P. J. pj#example.com
7 Aldrin Edwin "Buzz" buzz#example.com
Form layout:
VBA module for this form:
Option Compare Database
Option Explicit
Private Sub Form_Load()
Me.lstSearchResults.RowSource = ""
End Sub
Private Sub btnSearch_Click()
Me.lstSearchResults.SetFocus
Me.lstSearchResults.Value = Null
Me.lstSearchResults.RowSource = _
"SELECT ID, LastName, FirstName FROM Clients " & _
"WHERE LastName LIKE ""*" & DQ(Me.txtSearchLastName.Value) & _
"*"" AND FirstName LIKE ""*" & DQ(Me.txtSearchFirstName.Value) & "*"""
End Sub
Private Function DQ(s As Variant) As String
' double-up double quotes for SQL
DQ = Replace(Nz(s, ""), """", """""", 1, -1, vbBinaryCompare)
End Function
Private Sub btnLookupEmail_Click()
If IsNull(Me.lstSearchResults.Value) Then
Me.txtEmail.Value = ""
Else
Me.txtEmail.Value = DLookup("Email", "Clients", "ID=" & Me.lstSearchResults.Value)
End If
End Sub
When the form is first opened, everything is empty.
Typing "thompson" (without the quotes) and clicking btnSearch populates the List Box with clients WHERE LastName LIKE "*thompson*". (If you look at the code you'll see that it will also match on FirstName if you supply one.)
Select one of the items in the List Box and click btnLookupEmail and the email address is displayed in the Text Box below.