Updating selected items from List Mover to table (1 Viewer)

jason73503

New member
Local time
Yesterday, 18:29
Joined
Jul 26, 2017
Messages
8
Greetings Access World Forums,

This is my first post here on this wonderful website, and I'm hoping this fine community can help me resolve a simple problem for a confused newbie :eek:

I'm trying to pass selected items from a list box mover and assign it to a control source for my "VocabularyFocus" junction table.

The "VocabularyFocus" junction table has two primary key fields "VocabIDfk" and "UnitIDfk". The intent is to assign selected items to a specific unit within a Course book.

I have the following code for the list box, but I need a vba procedure for the cmdAssign_Click() in order to pass the selected items to a unit specified in "txtUnit" unbound box.

I figure I'll have to use a DoCmd.RunSQL or db.execute command, but I'm not sure how to structure it with the SQL statement :banghead:

Code:
Option Compare Database
Option Explicit

Private Sub cmdAdd_Click()

Dim in_clause As String: in_clause = ""
Dim strSQL As String, n As Integer

' ITERATE TO BUILD COMMA-SEPARATED LIST FOR SQL IN() CLAUSE
With Me.lfmVocabulary
    For n = 0 To .ListCount - 1
       If .Selected(n) = True Then
           in_clause = in_clause & .ItemData(n) & ", "
       End If
    Next n
End With

' REMOVE LAST COMMA AND SPACE
in_clause = Left(in_clause, Len(in_clause) - 2)

strSQL = "SELECT * FROM Vocabulary" _
           & " WHERE VocabID IN (" & in_clause & ")"

Me.lfmVocabularyAssign.RowSource = strSQL
Me.lfmVocabularyAssign.RowSourceType = "Table/Query"
Me.lfmVocabularyAssign.Requery

End Sub

Private Sub cmdAssign_Click()

Dim in_clause As String: in_clause = ""
Dim strSQL As String, n As Integer

With Me.lfmVocabularyAssign
    For n = 0 To .ListCount - 1
       If .Selected(n) = True Then
       DoCmd.RunSQL "UPDATE VocabularyFocus Set VocabIDfk = '"
       
       

End Sub

Private Sub cmdClearAll1_Click()
 
 Dim n As Integer
    
    With Me.lfmVocabulary
        For n = 0 To .ListCount - 1
            .Selected(n) = False
        Next n
    End With
    
End Sub

Private Sub cmdClearAll2_Click()

 Dim n As Integer
    
    With Me.lfmVocabularyAssign
        For n = 0 To .ListCount - 1
            .Selected(n) = False
        Next n
    End With
    
End Sub

Private Sub cmdRemove_Click()

Dim in_clause As String: in_clause = ""
Dim strSQL As String, n As Integer
'Set the SQL to the current SQL
strSQL = Me.lfmVocabularyAssign.RowSource


' ITERATE TO REMOVE ITEMS FROM COMMA-SEPARATED LIST FOR SQL IN() CLAUSE
With Me.lfmVocabularyAssign
    For n = 0 To .ListCount - 1
       If .Selected(n) = True Then
           If InStr(1, strSQL, ", " & .ItemData(n)) <> 0 Then
                'Not the first item, nor the only item
                strSQL = Replace(strSQL, ", " & .ItemData(n), "")
           ElseIf InStr(1, strSQL, .ItemData(n) & ", ") <> 0 Then
                'It's the first item
                strSQL = Replace(strSQL, .ItemData(n) & ", ", "")
            Else
                'It's the only item
                strSQL = Replace(strSQL, .ItemData(n), "")
            End If
       End If
    Next n
End With


Me.lfmVocabularyAssign.RowSource = strSQL
Me.lfmVocabularyAssign.RowSourceType = "Table/Query"
Me.lfmVocabularyAssign.Requery

End Sub
Private Sub cmdSelectAll1_Click()

 Dim n As Integer
    
    With Me.lfmVocabulary
        For n = 0 To .ListCount - 1
            .Selected(n) = True
        Next n
    End With
    
End Sub


Private Sub cmdSelectAll2_Click()
 Dim n As Integer
    
    With Me.lfmVocabularyAssign
        For n = 0 To .ListCount - 1
            .Selected(n) = True
        Next n
    End With
End Sub


Private Sub Form_Load()

    Me.lfmVocabularyAssign.RowSource = ""
    Me.lfmVocabulary.RowSource = "Vocabulary"
    Me.lfmVocabulary.RowSourceType = "Table/Query"
    Me.lfmVocabulary.Requery

End Sub

Private Sub txtSearchBox_Change()

    Dim strWhere As String
        With Me.txtSearchBox
          If .Text = vbNullString Then
          strWhere = "(False)"
        Else
          strWhere = "Vocabulary Like """ & .Text & "*"""
        End If
        End With
        
        With Me.lfmVocabulary
        .Filter = strWhere
        .FilterOn = True
        End With

End Sub
 

ashleedawg

"Here for a good time"
Local time
Yesterday, 18:29
Joined
Jun 22, 2017
Messages
154
From your description & code, it's tough to determine exactly what you're trying to accomplish. I find that when I'm having an issue with a complicated part of a database, it helps to create a new (temporary) database, kind of a simplified "mini reproduction", get that working, and add to it from there.

There are also some great tutorials that you might find useful, if you search Google or Youtube for "access vba tutorial working with list boxes" etc. :)
 

isladogs

MVP / VIP
Local time
Today, 02:29
Joined
Jan 14, 2017
Messages
18,209
I've skimmed your code and noticed some lines missing in cmdAssign - added in RED below

Code:
Private Sub cmdAssign_Click()

Dim in_clause As String: in_clause = ""
Dim strSQL As String, n As Integer

With Me.lfmVocabularyAssign
    For n = 0 To .ListCount - 1
       If .Selected(n) = True Then
            [COLOR="DarkGreen"]DoCmd.RunSQL "UPDATE VocabularyFocus Set VocabIDfk = '"[/COLOR]
        [COLOR="Red"]End If
    Next n
End With[/COLOR]   

End Sub

Also the DoCmd.RunSQL line marked in GREEN is incorrect.
Not sure what you are trying to set this value to.
If its an empty string you need
Code:
DoCmd.RunSQL "UPDATE VocabularyFocus Set VocabIDfk =[COLOR="red"]''[/COLOR]"
Otherwise something else (but I'm not clear what exactly you want) inside the 2 ' quotes

Please can you clarify exactly what you are trying to do

Also you are going to get update warnings for each action query as you haven't turned them off in your code.
If you are intending to do that once everything has been fixed, that's fine.

However, if you have globally switched action query warnings off, that's a bad idea.

Finally, I would add error handling code to each sub
 

ashleedawg

"Here for a good time"
Local time
Yesterday, 18:29
Joined
Jun 22, 2017
Messages
154
Attached is a fairly basic example of Combo Box / List Box data manipulation with multiple tables using VBA.
 

Attachments

  • listbox_example.accdb
    544 KB · Views: 57

jason73503

New member
Local time
Yesterday, 18:29
Joined
Jul 26, 2017
Messages
8
Yeah, it's quite a complex piece of code, took me awhile to get it to where it is.

However, Ridders, you found the section of code that I need assistance. The list box movers work perfectly, I just need to find a way to pass to selected items in the lfmVocabularyAssign list box to the table "VocabularyFocus"

I have no good idea on how to do this effectively. The code that I have is mostly a placeholder :D

Code:
Private Sub cmdAssign_Click()

Dim in_clause As String: in_clause = ""
Dim strSQL As String, n As Integer

With Me.lfmVocabularyAssign
    For n = 0 To .ListCount - 1
       If .Selected(n) = True Then
            DoCmd.RunSQL "UPDATE VocabularyFocus Set VocabIDfk = '"
        End If
    Next n
End With   

End Sub

I'm looking for the right code to assign the selected items to its respective table. I'm not sure if the fields should be primary keys or not.

VocabularyFocus (Table)
VocabIDfk (PK)
UnitIDfk (PK)

So when you click the cmdAssign button, you take the selected items from lfmVocabularyAssign listbox and pass the VocabID to VocabIDfk. Also, the UnitIDfk is referenced in a text box named txtUnit within the same form. I would like that value to be passed to UnitIDfk as well :D
 

isladogs

MVP / VIP
Local time
Today, 02:29
Joined
Jan 14, 2017
Messages
18,209
Thanks for explanation but I can't quite visualise what you want.
Suggest you upload a stripped down copy of your db so that one of us can look at it
 

jason73503

New member
Local time
Yesterday, 18:29
Joined
Jul 26, 2017
Messages
8
Ok guys,

Thanks so far for your continued assistance, and I'm sorry for my clear lack in my ability to explain my situation in terms everyone can understand.

That being said, and upon Ridders request, I am attaching a stripped version of my database.

Please take a look :)
 

Attachments

  • Testabase.accdb
    1.3 MB · Views: 44

isladogs

MVP / VIP
Local time
Today, 02:29
Joined
Jan 14, 2017
Messages
18,209
I've had a quick look at your db but there are various errors which i assume are due to stuff you've removed to upload this

1. There is a record source error when you open the main form
2. Only one record is shown in the form
3. On clicking the Units tab to get to the subform with the Assign button, the button isn't visible unless you shift items up in the tab
4. the txtUnit textbox shows a #Name error

Please can you fix those issues & upload again.

I believe that your cmdAssign button should use an APPEND query as I think you are trying to add new records to the VocabularyFocus table
An UPDATE query can't work here as you have no records in the table to update
 
Last edited:

jason73503

New member
Local time
Yesterday, 18:29
Joined
Jul 26, 2017
Messages
8
Ridders,

1) Fixed: I added the relevant tables and forms to fix this issue.

2) I imagine you mean there is only one record as being there is only one book being related to in the within the entire "Primary Book Details Extended" form. This is correct, I'm only working within one record as I've not gotten to handling the issue of figuring out how to reset the form after a "cmdSaveNew" event in order to clear and reset the form to allow for multiple records. I figure I'll cross that bridge when I figure out the workings of a single record.

3) Fixed: I readjusted the sizes to fit the subform into the main form

4) New problem: The event works in "Subform Book Unit Details" where when you change the record set using the controls, it passes the txtUnit from one text box within the main form "Subform Book Unit Details" to the subform "Subform Vocabulary Focus" txtUnit. I have no idea why this function doesn't work within the main form "Primary Book Details Extended"

5) I need to research APPEND queries as I'm new to this. How would I add this function to the VBA code within cmdAssign?
 

Attachments

  • Testabase.accdb
    1.5 MB · Views: 40

isladogs

MVP / VIP
Local time
Today, 02:29
Joined
Jan 14, 2017
Messages
18,209
Hi Jason

I've had a very long look at this and made some changes...
... BUT there is a long way to go

First the good news
1. I've fixed the BookID field in the main form - its now a bound control
2. I've linked all subforms to the main form using BookID as the Parent field & the equivalent as the child field.
You had done some links but not all
3. I've changed cboCourseBook to a textbox & used a DLookup function to get the value based on a new query qryCourseBook
However it doesn't update when you change the record
4. I've fixed the code in cmdAssign_Click using SQL to append the values
Its easier in such cases to create a query first & when you know its working paste that into the VBE
The query qryAppendTEST was used for this purpose.
I've left it in for you to look at but its no longer needed so can be deleted.

You'll notice that I've used CurrentDB.Execute rather than DoCmd.RunSQL
This stops warning messages appearing e.g. you are about to update 1 row.

The alternative is to use DoCmd.SetWarnings False before the strSQL code & DoCmd.SetWarnings True afterwards
However that will suppress additional messages which you don't want to hide

Either way, ALWAYS add detailed error handling in your code

Updated db is attached

Now several other comments - not so good & you may not like what I'm about to say
a) I never work with navigation forms as they are very difficult to adapt if you want to make any changes
My recommendation is you go back to square one and start again
Create your own forms/subforms from scratch building up each step as you go and checking each works before adding the next part

b) Similarly I never work with enbedded macros & nor do many of the regular contributors to this forum.
Recommend you stick to event procedures as they are more powerful & easier to understand once you get used to them
I expect there are things you need to change in the main Form_Load event but as its an EM I'm not even going to look at it.

c) Similarly I strongly recommend you look at your table structure and naming
There are several tables which seem to be duplicate or near duplicates

This also means your table relationships are much more complex than they should be.
Its not normal (at least in my experience) to see system tables (starting with MSys) in the relationships window.
Did you add them or was it the result of using an MS template to start with?

d) Avoid spaces and special characters such as / in field names - it makes coding FAR harder and is liable to lead to errors

e) Avoid reserved words in field names.
Most of your names are OK in that sense but I think 'Level' is reserved.
How about LevelName?

f) Tables with only one field (apart from the PK field which doesn't count in this context) are normally unnecessary.
These should be merged with other tables to simplify your structure
e.g. suggest merging VocabSpeech with VocabSpeechDefinitions ; merge Levels with ???

I recognise that you've put in a lot of effort so far & will therefore almost certainly want to persevere with this.
Some of the coding you have done is very good.
However if you carry on, your issues will become more & more complex to solve.
Eventually you will either give up or be forced to start again
Far better to start again now rather than later

If you follow my advice, plan out on paper the details of what you are trying to do - i.e. a 'business plan'
Use your plan to decide what tables are needed then draw a relationships diagram.
If necessary, ask forum users to comment on this before you proceed.
Several experienced forum members are excellent at analysing relationships & will be very helpful if asked
Recommend you don't touch Access again until the structure & relationships are correct to fulfil your plan

I've gone as far as I can with this as it is but perhaps others will be willing to step in here.
Good luck with your project whatever you decide to do
 

Attachments

  • Testabase v2 - CR.accdb
    1.2 MB · Views: 63
Last edited:

jason73503

New member
Local time
Yesterday, 18:29
Joined
Jul 26, 2017
Messages
8
Ridders,

I can't thank you enough! You're solution works and I can't express my gratitude for your time, attention, and expertise.

I tested some of the aspects of the changes you've made and I agree, I still have a long way to go to get it to where I want it. I'm still new to learning the program and programming, so thank you for helping me further my own understanding.

In regards to your post and proposals.

1. The BookID Bound control should also help me to create and reference that specific book in the future.

2. Also, by changing the parent/child field relationships, I imagine this will also allow all the data to be reset once I hit a cmdSaveNew event procedure to allow me to enter new book details. I tried this, but some of the subforms do not reset. I will look into this at a later time.

3. You stated that it doesn't update when I change the record. This is perfect for data-entry. Thanks so much for that added feature. It was another one of my fix-it items.

4. This was the meat and potatoes of my problem, again thanks so much! I now have the "Access 2016 Bible" to help me further understand this process. Hopefully I can learn something from it. One thing that is of concern for me is that once the selected items are assigned, I cannot delete them unless I go into the table. I guess I'll have to find a way to make a code for that as well.

a) By Navigation Forms, do you mean the Tab Controls in the Design ribbon? This is my one of many attempts at recreating and redesigning this database. Started with Alpha, and now I'm on Echo (A,B,C,D, and now E) :). Looks like I might need to start over on Foxtrot (F). The joy! :banghead:

b) I've heard the VBA Programming language was much better than the Macros, but one of my future ambitions is to put a version of this on the web for our teachers to filter and search. I imagine there are a couple options for this, but one thing I heard about Access 365 is that it only accepts Macros when updating to that version. I could be wrong though. Again, newbie here :D

c) Yeah, some of the tables came from a Microsoft Template, as well as much of the Event Macros.

f) Good points, I'll have to look into getting more help and testing these out. I think one of my biggest concerns is my table relationships. Once I have that completely sorted, I can go on with more confidence.

I will make a post on this website for further assistance. So far, you guys are much more responsive than StackOverflow, and some of your other competitors!
 

isladogs

MVP / VIP
Local time
Today, 02:29
Joined
Jan 14, 2017
Messages
18,209
By Navigation Forms, do you mean the Tab Controls in the Design ribbon? This is my one of many attempts at recreating and redesigning this database. Started with Alpha, and now I'm on Echo (A,B,C,D, and now E) . Looks like I might need to start over on Foxtrot (F). The joy!

b) I've heard the VBA Programming language was much better than the Macros, but one of my future ambitions is to put a version of this on the web for our teachers to filter and search. I imagine there are a couple options for this, but one thing I heard about Access 365 is that it only accepts Macros when updating to that version. I could be wrong though. Again, newbie here

c) Yeah, some of the tables came from a Microsoft Template, as well as much of the Event Macros.

f) Good points, I'll have to look into getting more help and testing these out. I think one of my biggest concerns is my table relationships. Once I have that completely sorted, I can go on with more confidence.

I will make a post on this website for further assistance. So far, you guys are much more responsive than StackOverflow, and some of your other competitors!

a) The type of form is called a navigation form. Fine if you want it do do exactly what the template provides but a nightmare to manage if not.
Bit like a satnav nagivating drivers the wrong way down a one way street

b) You're right that you can't use VBA with Access web apps BUT the bad news is these are currently being phased out.
Don't even start going down that road...even if your satnav keeps telling you to do so

c) Thought so - nothing wrong with that in itself

d) ?
e) ?
f) Suggest you post a screenshot of your relationships in a new thread.
Someone like plog, Minty or the Doc Man will almost certainly make excellent suggestions on what to do but I'm guessing will repeat my comments about table & relationship structure

I'm not likely to respond to that as I'm not so good at visualising relationships from screenshots as others on here

As for AWF vs other forums - I agree totally with you - I look at others but in different ways find all much less helpful than this site.
Feel free to post in more than one forum if you wish BUT if you do so, ALWAYS explain you are cross posting & give the links to the other site(s)
See this link about the etiquette of cross posting https://www.excelguru.ca/content.php?184#
 

Users who are viewing this thread

Top Bottom