• Pass Values from a Form to a Query (XP)

    Home » Forums » AskWoody support » Productivity software by function » MS Access and database help » Pass Values from a Form to a Query (XP)

    Author
    Topic
    #392507

    Hi

    A few weeks back, I posted a message regarding creating a Form that contained 2 List Boxes. The List Box on the Left would pull its data from a Query that contained all our Current Mailing List Members. When a User clicks an ‘ADD’ Command Button on the Form, the selected Mailing List would ‘move’ from the Available List Box to the Selected List Box. Hans very kindly provided code that would allow this to function, although it used a system whereby check boxes were turned on or off to indicate that a value had been selected. This would be great except that many, many people would be generating mail merges. However, leaving that aside, I purchased 2 books {SAMS Teach Yourself Access VBA (which was useless) and Access VBA Step By Step (which is terrific)} in the hope that I would learn how to pass values from a Form to a Query, but unfortunately neither provided a way to do such. Now I’m wondering is it possible to do this in Access VBA?

    Example:
    A user selects ‘All Members‘, ‘Additional Contacts‘, and ‘Leadership Team‘ from a List Box, and when the user hits an EXPORT Command Button, Code would run that passes the values into the query:

    SELECT company_details.name, company_details.address_1, company_details.town, company_details.postcode, list_details.list_name, personnel_details.name, personnel_details.salutation, personnel_details.title, company_details.active, company_list_details.active, list_details.active, personnel_details.active
    FROM ((company_details INNER JOIN company_list_details ON company_details.company_id = company_list_details.company_id) INNER JOIN list_details ON company_list_details.list_id = list_details.list_id) INNER JOIN personnel_details ON company_list_details.personnel_id = personnel_details.personnel_id
    WHERE (((list_details.list_name)=”ALL Members“) AND ((company_details.active)=”Y”) AND ((company_list_details.active)=”y”) AND ((list_details.active)=”y”) AND ((personnel_details.active)=”Y”)) OR (((list_details.list_name)=”Additional Contacts“) AND ((company_details.active)=”Y”) AND ((company_list_details.active)=”Y”) AND ((list_details.active)=”Y”) AND ((personnel_details.active)=”Y”))
    OR (((list_details.list_name)=”Leadership Team“) AND ((company_details.active)=”Y”) AND ((company_list_details.active)=”Y”) AND ((list_details.active)=”Y”) AND ((personnel_details.active)=”Y”))
    ORDER BY personnel_details.name;

    From what I’ve read, I do think this is possible, so I guess I’m asking if someone knows how to do this?

    Viewing 0 reply threads
    Author
    Replies
    • #705010

      The general answer to your question is “yes” and the specific answer is “no, not easily”.

      If is possible to refer to the value of a text box, combo box, check box etc. in a query, for instance you can set the condition for a field to

      [Forms]![frmSelect]![txtStartDate]

      But from your description, I guess that you have a multi-select list box. A multi-select list box doesn’t have “a” value, so you can’t refer to it the same way you can refer to a text box, or a single-select list box for that matter.

      You could write a VBA function to retrieve the selected values, and use that in the query, but it would be very inefficient, since the function would be run for each record in the table.

      You could write code that creates the SQL for the query, then saves it (but that might lead to problems in a multi-user environment, depending on how you set it up), or you can initiate the merge from Access and pass the SQL as data source. Advantage is that the SQL is dynamic, and presents no problems if multiple users are merging at the same time.

      This code is not trivial, but it can be done. Post back if you’re interested.

      • #705023

        Thanks Hans. As usual, you’re a star.

        Well, the List Box way of doing it is the way we would like it done, but would there be a better way that would make what I’m trying to do easier? I suppose I could add Fields to the ‘Lists’ Table for each user, e.g., Diana, Melanie, Heather, Hilary, Joanne, etc, and then the checkboxes could be set to True/Yes, whenever a user checked their name and ‘Added’ a List to the ‘Selected’ List Box.

        For example

        Heather checks her name and the names of the fields she wants included in the Mail Merge: Additonal Contacts and Members. Accordingly, the HEATHER checkboxes that correspond with Additional Contacts and Members change their values to TRUE. The query can then run by using . . .
        WHERE (((tblLists.Heather)=Yes));

        Would either of these be viable?

        • #705024

          Unless you really have to, I wouldn’t recommend adding fields to the table for each user. It is very inflexible – you would need to change the design of the table each time somebody leaves or joins the group of users.

          • #705025

            I was going to do that to see if it would make it easier b/c you said that what I wanted was very complicated. Do you think there’s a better solution that doesn’t involve List Boxes?

            • #705027

              List boxes are probably a good way to do this, and whatever method you use, it’ll take some work because multiple users must be able to merge different groups of records at the same time.

            • #705030

              [indent]


              . . . or you can initiate the merge from Access and pass the SQL as data source. Advantage is that the SQL is dynamic, and presents no problems if multiple users are merging at the same time. This code is not trivial, but it can be done. Post back if you’re interested.


              [/indent]

              OK. I’m interested!!! artist bow compute

            • #705032

              I’ll whip up an example for you later today.

            • #705047

              You da man!

            • #705057

              I have attached some sample code. Of course, you must substitute the correct names for the list box, document name etcetera.

            • #705059

              Hans salute

              That code is awesome, but I feel so guilty, b/c we use WordPerfect, so you wrote a lot of code that you didn’t need to Brian. sad .

              I was going to get the users to click the Export to Excel button, b/c I need to make sure that no duplicate values are included (some people can be on many lists).
              But I so appreciate your taking the time to do that. You’re awesome. I’ll look at the code tonight and try to get it to work, although I’m sure it will! smile

            • #705067

              I can’t help you then, I have no idea how to automate merging with WP. If it allows merging with a SQL string as data source, you may still be able to use the part of the code that constructs the SQL.

              (Don’t worry, I didn’t write the code for you, I just adapted something I had lying around.)

            • #705075

              Don’t worry! That’s totally cool. I just needed to know how to get the values from the List Boxes to the Query. That’s the most important part. Once the query has run, I’ll add a button to get the user to send it to Excel where they can play a macro that will remove duplicates.

              Once this is run, they just click a Macro in WordPerfect that merges using the Excel File as the Data Source.

              Thanks again. You have no idea how much I appreciate your help.

            • #735897

              Well, I’m on the last leg of the DB, and the last Form I need to get working is the one discussed in this thread. Thanks to Hans for the code he provided, but in my stupidity, I’ve hit a snag in that the code is a function, and (obviously) the OnClick Event is a sub. Could someone please explain how I add the Function to the OnClick Command Button, and is there a way to output the result to Excel (and then run a Macro in Excel that shows unique records).

              The Code that was posted is as follows:
              Private Function cmdMerge_Click()
              Dim strWhere As String
              Dim strSQL As String
              Dim strDoc As String
              Dim varItem As Variant

              If Me.lbxSelected.ItemsSelected.Count = 0 Then
              Exit Function
              End If

              strSQL = “SELECT tbl_list_details.list_name, tbl_personneldetails.name, tbl_personneldetails.title, tbl_personneldetails.salutation, tbl_branch.name, tbl_branch.address_1, tbl_branch.address_2, tbl_branch.town, tbl_branch.postcode, tbl_list_details.active, tbl_personneldetails.active, tbl_personneldetails.Alert
              FROM tbl_list_details INNER JOIN (tbl_branch INNER JOIN (tbl_personneldetails INNER JOIN tbl_company_list_details ON tbl_personneldetails.id_personnel = tbl_company_list_details.personnel_id) ON tbl_branch.branch_id = tbl_personneldetails.branch_id) ON tbl_list_details.list_id = tbl_company_list_details.list_id
              WHERE (((tbl_list_details.active)=True) AND ((tbl_personneldetails.active)=True) AND ((tbl_personneldetails.Alert)=False))
              ORDER BY tbl_list_details.list_name, tbl_personneldetails.name;”

              For Each varItem In Me.lbxSelected.ItemsSelected
              strWhere = strWhere & “, ‘” & lbxSelected.ItemData(varItem) & “‘”
              Next varItem
              ‘ Get rid of initial “, ”
              strWhere = Mid(strWhere, 3)

              strSQL = strSQL & strWhere & “) ” & _
              “ORDER BY personnel_details.name”
              End Function

              Here’s the Excel code that I want to run . . . can I just paste this into the end of the Function?
              Sub Macro1()

              ‘ Macro1 Macro
              ‘ Macro recorded 27/10/2003 by Brian


              Selection.EntireColumn.Delete
              ActiveWindow.Zoom = 50
              Columns(“I:K”).Select
              Selection.Delete Shift:=xlToLeft
              Range(“A1”).Select
              Selection.AutoFilter
              Range(“A1:H1159”).AdvancedFilter Action:=xlFilterInPlace, Unique:=True
              Range(“A1:H1159”).Select
              Selection.Copy
              Workbooks.Add
              Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
              :=False, Transpose:=False
              Application.CutCopyMode = False
              ActiveWorkbook.SaveAs Filename:= _
              “C:merge.xls”, FileFormat:= _
              xlNormal, Password:=””, WriteResPassword:=””, ReadOnlyRecommended:=False _
              , CreateBackup:=False
              End Sub

              Thanks in advance for your help. I couldn’t have come this far without you.

            • #735907

              blush Stupid mistake on my side. You can just replace Function by Sub:

              Private Sub cmdMerge_Click()

              If Me.lbxSelected.ItemsSelected.Count = 0 Then
              Exit Sub
              End If

              End Sub

              However, the SQL as modified by you won’t work. Please go back to my code and see how the SQL is constructed. You can’t use a complete SQL statement including a WHERE condition and then append another WHERE condition to it.

              If you want to weed out duplicates, you can do that in the SQL statement, by inserting DISTINCT after SELECT:

              strSQL = “SELECT DISTINCT tbl_list_details.list_name …

              Easier and faster than using advanced filter in Excel.

              There are several ways to transfer the output of the SQL statement to Excel: create a query with this SQL statement and using DoCmd.TransferSpreadsheet or DoCmd.OutputTo to export it to Excel, or use CopyFromRecordset in a macro in Excel.

            • #736255

              Thanks Hans

              I’ve modified the code and compiled it, which ‘seems’ good, as it compile w/o problems . . . but (naturally for me), nothing happens.

              Here’s the code:
              Private Sub cmd_click_Click()
              Dim strWhere As String
              Dim strSQL As String
              Dim strDoc As String
              Dim varItem As Variant

              If Me.lbxSelected.ItemsSelected.Count = 0 Then
              Exit Sub
              End If

              strSQL = “SELECT DISTINCT tbl_list_details.list_name, tbl_personneldetails.name, ” & _
              “tbl_personneldetails.title, tbl_personneldetails.salutation, ” & _
              “tbl_branch.name, tbl_branch.address_1, tbl_branch.address_2, ” & _
              “tbl_branch.town, tbl_branch.postcode, tbl_list_details.active, ” & _
              “tbl_personneldetails.active, tbl_personneldetails.Alert” & _
              “FROM tbl_list_details INNER JOIN (tbl_branch INNER JOIN” & _
              “(tbl_personneldetails INNER JOIN tbl_company_list_details ON” & _
              “tbl_personneldetails.id_personnel = tbl_company_list_details.personnel_id) ” & _
              “ON tbl_branch.branch_id = tbl_personneldetails.branch_id) ” & _
              “ON tbl_list_details.list_id = tbl_company_list_details.list_id” & _
              “WHERE (((tbl_list_details.active)=True) AND” & _
              “((tbl_personneldetails.active)=True) AND” & _
              “((tbl_personneldetails.Alert)=False));”

              For Each varItem In Me.lbxSelected.ItemsSelected
              strWhere = strWhere & “, ‘” & lbxSelected.ItemData(varItem) & “‘”
              Next varItem
              ‘ Get rid of initial “, ”
              strWhere = Mid(strWhere, 3)

              strSQL = strSQL & strWhere & “) ” & _
              “ORDER BY tbl_list_details.list_name, tbl_personneldetails.name”
              DoCmd.OutputTo acOutputQuery, , acFormatXLS, “C:merge.xls”, True

              End Sub

              I tried both the DoCmd & Output To, but nothing seems to be happening? confused

              Help. blush

            • #736263

              1. As I pointed out before, you are creating an invalid SQL string. You end the string with ; and then append something after it. Change it to this (cf. the attachment I posted in August):

              strSQL =

              “((tbl_personneldetails.Alert)=False)) And list_details.list_name In (“

              For Each varItem …

              2. You create an SQL string but you don’t do anything with it. In the code I posted earlier, it was passed as an argument to StartWord, but you took that out, so now nothing happens.

              Create a selection query; it doesn’t matter what it does; for instance select the list_name field from the tbl_list_details. Save this query as qryTemp. At the end of the code, replace the line with OutputTo by

              CurrentDb.QueryDefs(“qryTemp”).SQL = strSQL
              DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, “qryTemp”, “C:Merge.xls”, True

              I prefer TransferSpreadsheet to OutputTo because OutputTo procduces an Excel 5 worksheet, with TransferSpreadsheet you can specify which version you want.

            • #736289

              Ready to scream yet?

              Sorry for the oversight with the semicolon. I had paid so much attention to adding the ampersands, etc, that I didn’t notice the semicolon, etc at the end. sad

              Anyway, I’ve read your post 3 times and very carefully made the modifications you stated. The Sub now looks like this:
              Private Sub cmd_click_Click()
              Dim strWhere As String
              Dim strSQL As String
              Dim strDoc As String
              Dim varItem As Variant

              If Me.lbxSelected.ItemsSelected.Count = 0 Then
              Exit Sub
              End If

              strSQL = “SELECT DISTINCT tbl_list_details.list_name, tbl_personneldetails.name, ” & _
              “tbl_personneldetails.title, tbl_personneldetails.salutation, ” & _
              “tbl_branch.name, tbl_branch.address_1, tbl_branch.address_2, ” & _
              “tbl_branch.town, tbl_branch.postcode, tbl_list_details.active, ” & _
              “tbl_personneldetails.active, tbl_personneldetails.Alert” & _
              “FROM tbl_list_details INNER JOIN (tbl_branch INNER JOIN” & _
              “(tbl_personneldetails INNER JOIN tbl_company_list_details ON” & _
              “tbl_personneldetails.id_personnel = tbl_company_list_details.personnel_id) ” & _
              “ON tbl_branch.branch_id = tbl_personneldetails.branch_id) ” & _
              “ON tbl_list_details.list_id = tbl_company_list_details.list_id” & _
              “WHERE (((tbl_list_details.active)=True) AND” & _
              “((tbl_personneldetails.active)=True) AND” & _
              “((tbl_personneldetails.Alert)=False)) And list_details.list_name In (”

              For Each varItem In Me.lbxSelected.ItemsSelected
              strWhere = strWhere & “, ‘” & lbxSelected.ItemData(varItem) & “‘”
              Next varItem
              ‘ Get rid of initial “, ”
              strWhere = Mid(strWhere, 3)

              strSQL = strSQL & strWhere & “) ” & _
              “ORDER BY tbl_list_details.list_name, tbl_personneldetails.name”
              CurrentDb.QueryDefs(“qry_temp”).SQL = strSQL
              DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, “qry_temp”, “C:Merge.xls”, True
              End Sub

              Anyway, it appears that I have 3 problems:
              (1) Unless an item in the Selected List Box is actually ‘selected’ (ie, clicked, not just in the Selected List Box), nothing happens.
              (2) The code isn’t executing on all the items in the list box, only 1 item
              (3) If I do click an item, then the code runs but a debug window (3075) comes up pointing me to this line of code:
              CurrentDb.QueryDefs(“qry_temp”).SQL = strSQL

              There *definitely* is a query called qry_temp, so the 3075 error is v. confusing???

              Sorry. sad

            • #736295

              About (1) and (2): the code I posted was for a multi-select list box. Change

              Dim varItem As Variant

              If Me.lbxSelected.ItemsSelected.Count = 0 Then
              Exit Sub
              End If

              to

              Dim i As Long

              If Me.lbxSelected.ListCount = 0 Then
              Exit Sub
              End If

              and

              For Each varItem In Me.lbxSelected.ItemsSelected
              strWhere = strWhere & “, ‘” & lbxSelected.ItemData(varItem) & “‘”
              Next varItem

              to

              For i = 0 To Me.lbxSelected.ListCount – 1
              strWhere = strWhere & “, ‘” & lbxSelected.ItemData(i) & “‘”
              Next i

              (3) To check what is happening, insert Debug.Print strSQL immediately above the line with CurrentDb.QueryDefs… When you get the error, the SQL string has been written to the Immediate window in the Visual Basic Editor. Copy it from there into a reply.

            • #736475

              Far out Hans, I *SO* couldn’t do this without you!

              Anyway, I’ve changed the code, and now clicking the Command Button works without clicking a List Box, so that’s cool! Almost there (D.V.)!

              Here’s the new Code. I’ve run the Query to make sure it works, then I modified it with the ” & _ to break it up:

              Private Sub cmd_click_Click()
              Dim strWhere As String
              Dim strSQL As String
              Dim strDoc As String
              Dim i As Long

              If Me.lbxSelected.ListCount = 0 Then
              Exit Sub
              End If

              strSQL = “SELECT DISTINCT tbl_list_details.list_name, tbl_personneldetails.name, tbl_personneldetails.title, ” & _
              “tbl_branch.name, tbl_branch.address_1, tbl_branch.address_2, tbl_branch.town, tbl_branch.postcode, ” & _
              “tbl_personneldetails.salutation, tbl_branch.active, tbl_personneldetails.active, tbl_personneldetails.Alert, ” & _
              “tbl_list_details.active ” & _
              “FROM (tbl_branch INNER JOIN tbl_personneldetails ON” & _
              “tbl_branch.branch_id = tbl_personneldetails.branch_id) INNER JOIN” & _
              “(tbl_company_list_details INNER JOIN tbl_list_details ON” & _
              “tbl_company_list_details.list_id = tbl_list_details.list_id) ON” & _
              “tbl_personneldetails.id_personnel = tbl_company_list_details.personnel_id ” & _
              “WHERE (((tbl_branch.active)=True) AND” & _
              “((tbl_personneldetails.active)=True) AND” & _
              “((tbl_personneldetails.Alert)=False) AND ((tbl_list_details.active)=True)) And tbl_list_details.list_name In (”
              For i = 0 To Me.lbxSelected.ListCount – 1
              strWhere = strWhere & “, ‘” & lbxSelected.ItemData(i) & “‘”
              Next i
              ‘ Get rid of initial “, ”
              strWhere = Mid(strWhere, 3)

              strSQL = strSQL & strWhere & “) ” & _
              “ORDER BY tbl_list_details.list_name, tbl_personneldetails.name”
              Debug.Print strSQL
              CurrentDb.QueryDefs(“qry_temp”).SQL = strSQL
              DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, “qry_temp”, “C:Merge.xls”, True
              End Sub

              The code from the Immediate Window is attached (as it made this post long) . . .

              Hope It Helps!

              Thanks again!

            • #736476

              The only thing that strikes me is that there is no space between ON and the table names in the FROM part of the SQL string. I don’t know if that’s serious, but I would replace

              ... ON" & _

              by

              ... ON " & _

              Do this three times. Do you still get the 3075 error then?

            • #736671

              Well Hans, you are definitely my hero!

              Those extra spaces were indeed the problem.

              The Code works beautifully, except for the Distinct part, but I kind of knew that wouldn’t work, as each record is Distinct from every other record: The List Name makes it unique, i.e., John Smith who works for Microsoft can be on two lists: Additional Contacts and Environmental Contacts.
              Therefore, when Access runs the query, it sees
              John Smith, Microsoft, Additional Contacts
              John Smith, Microsoft, Environmental Contacts

              These are obviously different, even thought they are technically duplicates.

              What my Macro did in Excel was to delete the Column that contained the List Name then it Filtered Unique Records. Without the List Name, the records looked like
              John Smith, Microsoft
              John Smith, Microsoft

              And this allowed it to see that there were 2 records the same and thus remove the duplicate.

              Unless there’s a way to get Access to ignore a field when it checks for duplicates, I’ll just need to get Excel to run the macro I mentioned above. Speaking of which, can I append that Macro code to the VBA subroutine?

            • #736673

              Do you need the List Name in the query results? If you’re going to delete the column in Excel, you might as well omit it from the query.

            • #736687

              The List Name is the most important field
              I.E., I want to send letters to all the people on the Additional Contacts List and the Environment List (for example).

              So, I select these 2 Lists from the Available List Box and Send them to the Selected List Box.
              The Query then runs and looks at the List Names I selected. Based on these selected items, the query pulls all the names and addresses that correspond to the people on the selected Lists. Without the List Names, how would the query work?

              I’m really confused

            • #736691

              Well, of course you need the List_Name field in the WHERE part of the query, because you want to select people occurring in selected lists. But, as far as I can see, you don’t need List_Name in the eventual address list. If that is correct, you can omit tbl_list_details.list_name from the SELECT part of the SQL; this would let DISTINCT take care of the duplicates. I can’t judge whether you need tbl_list_details.list_name in the ORDER BY clause.

            • #736741

              Oh, well that just shows what a novice I am. I thought I needed the fields in the WHERE part of the query to correspond to the SELECT part of the query!

              OK, I’ll try that. Thanks heaps.

              I’ll let you know (but you knew that . . . wink )

            • #736809

              If you open a query in design view, there is a Show check box for each field. If you clear this check box, the field won’t be displayed, i.e. it is removed from the SELECT part, but you can still use it to specify selection criteria or the sort order, i.e. it can still occur in the WHERE and ORDER BY parts.

            • #736810

              If you open a query in design view, there is a Show check box for each field. If you clear this check box, the field won’t be displayed, i.e. it is removed from the SELECT part, but you can still use it to specify selection criteria or the sort order, i.e. it can still occur in the WHERE and ORDER BY parts.

            • #736853

              Believe it or not, I did know that, i.e., that I could show or hide fields in the resulting display. However, I didn’t realize that by unchecking that box, Access didn’t then Select those Fields when it ran the query, thus enabling it to peform a DISTINCT operation on it. I just never looked at the SQL in those instances (rarely do).
              I thought Access still selected the data but then hid it from view when the Query opened.

              I’m going to modify the SQL tonite, so DV, I’ll be in business.

              You have been so great Hans–I really don’t know how to thank you for all your help. It’s been above-and-beyond the call of duty! Thanks again, so much. bravo
              I hope I don’t have to torture you again!

            • #736854

              Believe it or not, I did know that, i.e., that I could show or hide fields in the resulting display. However, I didn’t realize that by unchecking that box, Access didn’t then Select those Fields when it ran the query, thus enabling it to peform a DISTINCT operation on it. I just never looked at the SQL in those instances (rarely do).
              I thought Access still selected the data but then hid it from view when the Query opened.

              I’m going to modify the SQL tonite, so DV, I’ll be in business.

              You have been so great Hans–I really don’t know how to thank you for all your help. It’s been above-and-beyond the call of duty! Thanks again, so much. bravo
              I hope I don’t have to torture you again!

            • #736742

              Oh, well that just shows what a novice I am. I thought I needed the fields in the WHERE part of the query to correspond to the SELECT part of the query!

              OK, I’ll try that. Thanks heaps.

              I’ll let you know (but you knew that . . . wink )

            • #736692

              Well, of course you need the List_Name field in the WHERE part of the query, because you want to select people occurring in selected lists. But, as far as I can see, you don’t need List_Name in the eventual address list. If that is correct, you can omit tbl_list_details.list_name from the SELECT part of the SQL; this would let DISTINCT take care of the duplicates. I can’t judge whether you need tbl_list_details.list_name in the ORDER BY clause.

            • #736688

              The List Name is the most important field
              I.E., I want to send letters to all the people on the Additional Contacts List and the Environment List (for example).

              So, I select these 2 Lists from the Available List Box and Send them to the Selected List Box.
              The Query then runs and looks at the List Names I selected. Based on these selected items, the query pulls all the names and addresses that correspond to the people on the selected Lists. Without the List Names, how would the query work?

              I’m really confused

            • #736674

              Do you need the List Name in the query results? If you’re going to delete the column in Excel, you might as well omit it from the query.

            • #736672

              Well Hans, you are definitely my hero!

              Those extra spaces were indeed the problem.

              The Code works beautifully, except for the Distinct part, but I kind of knew that wouldn’t work, as each record is Distinct from every other record: The List Name makes it unique, i.e., John Smith who works for Microsoft can be on two lists: Additional Contacts and Environmental Contacts.
              Therefore, when Access runs the query, it sees
              John Smith, Microsoft, Additional Contacts
              John Smith, Microsoft, Environmental Contacts

              These are obviously different, even thought they are technically duplicates.

              What my Macro did in Excel was to delete the Column that contained the List Name then it Filtered Unique Records. Without the List Name, the records looked like
              John Smith, Microsoft
              John Smith, Microsoft

              And this allowed it to see that there were 2 records the same and thus remove the duplicate.

              Unless there’s a way to get Access to ignore a field when it checks for duplicates, I’ll just need to get Excel to run the macro I mentioned above. Speaking of which, can I append that Macro code to the VBA subroutine?

            • #736477

              The only thing that strikes me is that there is no space between ON and the table names in the FROM part of the SQL string. I don’t know if that’s serious, but I would replace

              ... ON" & _

              by

              ... ON " & _

              Do this three times. Do you still get the 3075 error then?

            • #736296

              About (1) and (2): the code I posted was for a multi-select list box. Change

              Dim varItem As Variant

              If Me.lbxSelected.ItemsSelected.Count = 0 Then
              Exit Sub
              End If

              to

              Dim i As Long

              If Me.lbxSelected.ListCount = 0 Then
              Exit Sub
              End If

              and

              For Each varItem In Me.lbxSelected.ItemsSelected
              strWhere = strWhere & “, ‘” & lbxSelected.ItemData(varItem) & “‘”
              Next varItem

              to

              For i = 0 To Me.lbxSelected.ListCount – 1
              strWhere = strWhere & “, ‘” & lbxSelected.ItemData(i) & “‘”
              Next i

              (3) To check what is happening, insert Debug.Print strSQL immediately above the line with CurrentDb.QueryDefs… When you get the error, the SQL string has been written to the Immediate window in the Visual Basic Editor. Copy it from there into a reply.

            • #736290

              Ready to scream yet?

              Sorry for the oversight with the semicolon. I had paid so much attention to adding the ampersands, etc, that I didn’t notice the semicolon, etc at the end. sad

              Anyway, I’ve read your post 3 times and very carefully made the modifications you stated. The Sub now looks like this:
              Private Sub cmd_click_Click()
              Dim strWhere As String
              Dim strSQL As String
              Dim strDoc As String
              Dim varItem As Variant

              If Me.lbxSelected.ItemsSelected.Count = 0 Then
              Exit Sub
              End If

              strSQL = “SELECT DISTINCT tbl_list_details.list_name, tbl_personneldetails.name, ” & _
              “tbl_personneldetails.title, tbl_personneldetails.salutation, ” & _
              “tbl_branch.name, tbl_branch.address_1, tbl_branch.address_2, ” & _
              “tbl_branch.town, tbl_branch.postcode, tbl_list_details.active, ” & _
              “tbl_personneldetails.active, tbl_personneldetails.Alert” & _
              “FROM tbl_list_details INNER JOIN (tbl_branch INNER JOIN” & _
              “(tbl_personneldetails INNER JOIN tbl_company_list_details ON” & _
              “tbl_personneldetails.id_personnel = tbl_company_list_details.personnel_id) ” & _
              “ON tbl_branch.branch_id = tbl_personneldetails.branch_id) ” & _
              “ON tbl_list_details.list_id = tbl_company_list_details.list_id” & _
              “WHERE (((tbl_list_details.active)=True) AND” & _
              “((tbl_personneldetails.active)=True) AND” & _
              “((tbl_personneldetails.Alert)=False)) And list_details.list_name In (”

              For Each varItem In Me.lbxSelected.ItemsSelected
              strWhere = strWhere & “, ‘” & lbxSelected.ItemData(varItem) & “‘”
              Next varItem
              ‘ Get rid of initial “, ”
              strWhere = Mid(strWhere, 3)

              strSQL = strSQL & strWhere & “) ” & _
              “ORDER BY tbl_list_details.list_name, tbl_personneldetails.name”
              CurrentDb.QueryDefs(“qry_temp”).SQL = strSQL
              DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, “qry_temp”, “C:Merge.xls”, True
              End Sub

              Anyway, it appears that I have 3 problems:
              (1) Unless an item in the Selected List Box is actually ‘selected’ (ie, clicked, not just in the Selected List Box), nothing happens.
              (2) The code isn’t executing on all the items in the list box, only 1 item
              (3) If I do click an item, then the code runs but a debug window (3075) comes up pointing me to this line of code:
              CurrentDb.QueryDefs(“qry_temp”).SQL = strSQL

              There *definitely* is a query called qry_temp, so the 3075 error is v. confusing???

              Sorry. sad

            • #736264

              1. As I pointed out before, you are creating an invalid SQL string. You end the string with ; and then append something after it. Change it to this (cf. the attachment I posted in August):

              strSQL =

              “((tbl_personneldetails.Alert)=False)) And list_details.list_name In (“

              For Each varItem …

              2. You create an SQL string but you don’t do anything with it. In the code I posted earlier, it was passed as an argument to StartWord, but you took that out, so now nothing happens.

              Create a selection query; it doesn’t matter what it does; for instance select the list_name field from the tbl_list_details. Save this query as qryTemp. At the end of the code, replace the line with OutputTo by

              CurrentDb.QueryDefs(“qryTemp”).SQL = strSQL
              DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, “qryTemp”, “C:Merge.xls”, True

              I prefer TransferSpreadsheet to OutputTo because OutputTo procduces an Excel 5 worksheet, with TransferSpreadsheet you can specify which version you want.

            • #736256

              Thanks Hans

              I’ve modified the code and compiled it, which ‘seems’ good, as it compile w/o problems . . . but (naturally for me), nothing happens.

              Here’s the code:
              Private Sub cmd_click_Click()
              Dim strWhere As String
              Dim strSQL As String
              Dim strDoc As String
              Dim varItem As Variant

              If Me.lbxSelected.ItemsSelected.Count = 0 Then
              Exit Sub
              End If

              strSQL = “SELECT DISTINCT tbl_list_details.list_name, tbl_personneldetails.name, ” & _
              “tbl_personneldetails.title, tbl_personneldetails.salutation, ” & _
              “tbl_branch.name, tbl_branch.address_1, tbl_branch.address_2, ” & _
              “tbl_branch.town, tbl_branch.postcode, tbl_list_details.active, ” & _
              “tbl_personneldetails.active, tbl_personneldetails.Alert” & _
              “FROM tbl_list_details INNER JOIN (tbl_branch INNER JOIN” & _
              “(tbl_personneldetails INNER JOIN tbl_company_list_details ON” & _
              “tbl_personneldetails.id_personnel = tbl_company_list_details.personnel_id) ” & _
              “ON tbl_branch.branch_id = tbl_personneldetails.branch_id) ” & _
              “ON tbl_list_details.list_id = tbl_company_list_details.list_id” & _
              “WHERE (((tbl_list_details.active)=True) AND” & _
              “((tbl_personneldetails.active)=True) AND” & _
              “((tbl_personneldetails.Alert)=False));”

              For Each varItem In Me.lbxSelected.ItemsSelected
              strWhere = strWhere & “, ‘” & lbxSelected.ItemData(varItem) & “‘”
              Next varItem
              ‘ Get rid of initial “, ”
              strWhere = Mid(strWhere, 3)

              strSQL = strSQL & strWhere & “) ” & _
              “ORDER BY tbl_list_details.list_name, tbl_personneldetails.name”
              DoCmd.OutputTo acOutputQuery, , acFormatXLS, “C:merge.xls”, True

              End Sub

              I tried both the DoCmd & Output To, but nothing seems to be happening? confused

              Help. blush

            • #735908

              blush Stupid mistake on my side. You can just replace Function by Sub:

              Private Sub cmdMerge_Click()

              If Me.lbxSelected.ItemsSelected.Count = 0 Then
              Exit Sub
              End If

              End Sub

              However, the SQL as modified by you won’t work. Please go back to my code and see how the SQL is constructed. You can’t use a complete SQL statement including a WHERE condition and then append another WHERE condition to it.

              If you want to weed out duplicates, you can do that in the SQL statement, by inserting DISTINCT after SELECT:

              strSQL = “SELECT DISTINCT tbl_list_details.list_name …

              Easier and faster than using advanced filter in Excel.

              There are several ways to transfer the output of the SQL statement to Excel: create a query with this SQL statement and using DoCmd.TransferSpreadsheet or DoCmd.OutputTo to export it to Excel, or use CopyFromRecordset in a macro in Excel.

            • #735898

              Well, I’m on the last leg of the DB, and the last Form I need to get working is the one discussed in this thread. Thanks to Hans for the code he provided, but in my stupidity, I’ve hit a snag in that the code is a function, and (obviously) the OnClick Event is a sub. Could someone please explain how I add the Function to the OnClick Command Button, and is there a way to output the result to Excel (and then run a Macro in Excel that shows unique records).

              The Code that was posted is as follows:
              Private Function cmdMerge_Click()
              Dim strWhere As String
              Dim strSQL As String
              Dim strDoc As String
              Dim varItem As Variant

              If Me.lbxSelected.ItemsSelected.Count = 0 Then
              Exit Function
              End If

              strSQL = “SELECT tbl_list_details.list_name, tbl_personneldetails.name, tbl_personneldetails.title, tbl_personneldetails.salutation, tbl_branch.name, tbl_branch.address_1, tbl_branch.address_2, tbl_branch.town, tbl_branch.postcode, tbl_list_details.active, tbl_personneldetails.active, tbl_personneldetails.Alert
              FROM tbl_list_details INNER JOIN (tbl_branch INNER JOIN (tbl_personneldetails INNER JOIN tbl_company_list_details ON tbl_personneldetails.id_personnel = tbl_company_list_details.personnel_id) ON tbl_branch.branch_id = tbl_personneldetails.branch_id) ON tbl_list_details.list_id = tbl_company_list_details.list_id
              WHERE (((tbl_list_details.active)=True) AND ((tbl_personneldetails.active)=True) AND ((tbl_personneldetails.Alert)=False))
              ORDER BY tbl_list_details.list_name, tbl_personneldetails.name;”

              For Each varItem In Me.lbxSelected.ItemsSelected
              strWhere = strWhere & “, ‘” & lbxSelected.ItemData(varItem) & “‘”
              Next varItem
              ‘ Get rid of initial “, ”
              strWhere = Mid(strWhere, 3)

              strSQL = strSQL & strWhere & “) ” & _
              “ORDER BY personnel_details.name”
              End Function

              Here’s the Excel code that I want to run . . . can I just paste this into the end of the Function?
              Sub Macro1()

              ‘ Macro1 Macro
              ‘ Macro recorded 27/10/2003 by Brian


              Selection.EntireColumn.Delete
              ActiveWindow.Zoom = 50
              Columns(“I:K”).Select
              Selection.Delete Shift:=xlToLeft
              Range(“A1”).Select
              Selection.AutoFilter
              Range(“A1:H1159”).AdvancedFilter Action:=xlFilterInPlace, Unique:=True
              Range(“A1:H1159”).Select
              Selection.Copy
              Workbooks.Add
              Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
              :=False, Transpose:=False
              Application.CutCopyMode = False
              ActiveWorkbook.SaveAs Filename:= _
              “C:merge.xls”, FileFormat:= _
              xlNormal, Password:=””, WriteResPassword:=””, ReadOnlyRecommended:=False _
              , CreateBackup:=False
              End Sub

              Thanks in advance for your help. I couldn’t have come this far without you.

            • #705076

              Don’t worry! That’s totally cool. I just needed to know how to get the values from the List Boxes to the Query. That’s the most important part. Once the query has run, I’ll add a button to get the user to send it to Excel where they can play a macro that will remove duplicates.

              Once this is run, they just click a Macro in WordPerfect that merges using the Excel File as the Data Source.

              Thanks again. You have no idea how much I appreciate your help.

            • #705068

              I can’t help you then, I have no idea how to automate merging with WP. If it allows merging with a SQL string as data source, you may still be able to use the part of the code that constructs the SQL.

              (Don’t worry, I didn’t write the code for you, I just adapted something I had lying around.)

            • #705060

              Hans salute

              That code is awesome, but I feel so guilty, b/c we use WordPerfect, so you wrote a lot of code that you didn’t need to Brian. sad .

              I was going to get the users to click the Export to Excel button, b/c I need to make sure that no duplicate values are included (some people can be on many lists).
              But I so appreciate your taking the time to do that. You’re awesome. I’ll look at the code tonight and try to get it to work, although I’m sure it will! smile

            • #737033

              Thank you so much for this great code sample Hans!

            • #737196

              Hi Hans

              I zipped and sent the Database through to my Office today, and–surprisingly–when I clicked the Merge Command Button, something weird happened. It ran the merge, but when I opened the Excel file, the data was all messed up, e.g., the person’s name was in the active column, etc. Surprised, I clicked the Command Button again, but I just got an error message:

              External table is not in the expected format. (Error 3274)
              The format of the table has changed since it was linked. Link the table again, and then retry the operation.

              Both PCs are running Windows XP with Excel 2003 (Beta 2 at home and final Beta at work).

              I’m wondering if the near-gold and gold versions of Access need a new version of Excel stipulated, eg, acSpreadsheetTypeExcel10/11 instead of 9. What do you think?

              I did a few searches on Google, and some people reported some problems between Office 97 and 2000. I’ll–obviously–search further if you’re unsure why this happened, but I just thought you might know off the top of your head. If you don’t, that’s cool. As stated, I’ll ‘google’ it.

            • #737206

              I thought that the Excel file format hadn’t changed, but I don’t have Office 2003. Perhaps someone with Office 2003 can help here.

            • #738404

              Hi Hans

              Thought I’d let you know that I purchased and installed MSOffice 2003 this week, and I’ve tested my Database on the full version, and it works perfectly, so I don’t think there’s a problem with referencing Excel as Excel9.

              However, as stated, I got 2 error messages at work–one per PC, so I’ll try another PC on Monday to see if the code keeps giving me errors. If it does, I don’t know whether you’ll have suggestions or whether I should just try to make do with each user having a separate Check Box that he or she selects in a personalized Query. On that point, I know that one of the reasons you helped me (well, actually, you did virtually everything) was so that I wouldn’t have to rely on check box in a Table, but when I was reviewing the code, I noticed that the ADD and Remove Command Buttons do actually select and deselect a Check Box in a the tbl_List _Details. So, now I’m wondering if this doesn’t defeat the purpose of the complex VBA code you wrote, as the idea was to elimate the need for multiple Yes/No Fields. As it stands, if multiple people were using this Merge feature, the ‘Selected’ Check Box would be selecting and deselting constantly, and the Feature would be unusable?

              Sorry to be a pain–as always, I appreciate your insight and help.

              You truly have the patience of a Saint!

            • #738406

              If the export works well on one PC with Office 2003, the problem apparently isn’t caused by the new Office version. I’m afraid I have no idea what else it could be, and there is no way for me to test this.

              You are correct that having a single Yes/No field to indicate which items have been added to the list box on the right will cause problems in a multi-user situation. But creating a separate Yes/No field for each user is going to be a nightmare to maintain – you would have to modify the design of the table and of the form each time the group of users changes. I pointed out some possibilities to make the list boxes work in a multi-user environment in post 282536: either set the Row Source Type to List instead of Table/Query, or use temporary tables in the local front end database.

            • #738608

              Thanks Hans! I had forgotten about that thread!

              I changed the Row Source Type to ‘Value List’ and set the Form’s ‘OnLoad’ Event to
              Private Sub Form_Load()
              lbxAvailable.RowSource = “tbl_list_details.list_name”
              End Sub

              . . . in order for it to populate the Available List Box.

              This kinda works in that the value is there in the Available List Box, and I can ‘send’ the item to the Selected List Box, but of course the value shouldn’t read ‘tbl_list_details.list_name”. It should obviously have the name of each List.

              I’ve never ‘populated’ an Item via code, so my attempt to do so is obviously incorrect. Once again, I am forced to ask you for the syntax I would need in order to populate said list.

              I’m sure you’re wishing I had just created multiple Yes/No Fields for each user, huh? flee

            • #738692

              If you set the Row Source Type property to Value List, the Row Source itself must be a … value list, not the name of a table or query. You must fill the “available” list box when you open the form. Here is demo code for a form with list boxes lbxAvailable and lbxSelected and command buttons cmdAdd and cmdRemove. The table used to populate lbxAvailable is tblMailingList, with two fields: ListID (AutoNumber, primary key) and MailingList (text).

              Here is the code for the form – of course you must adapt it to your situation:

              ‘ On Click event procedure for cmdAdd
              ‘ Moves selected item from lbxAvailable to lbxSelected

              Private Sub cmdAdd_Click()
              If Me.lbxAvailable.ListIndex > -1 Then
              Me.lbxSelected.AddItem Me.lbxAvailable.Column(0) & “;” & Me.lbxAvailable.Column(1)
              Me.lbxAvailable.RemoveItem Me.lbxAvailable.ListIndex
              End If
              End Sub

              ‘ On Click event procedure for cmdRemove
              ‘ Moves selected item from lbxSelected back to lbxAvailable

              Private Sub cmdRemove_Click()
              If Me.lbxSelected.ListIndex > -1 Then
              Me.lbxAvailable.AddItem Me.lbxSelected.Column(0) & “;” & Me.lbxSelected.Column(1)
              Me.lbxSelected.RemoveItem Me.lbxSelected.ListIndex
              End If
              End Sub

              ‘ On Load procedure for form
              ‘ Populates lbxAvailable

              Private Sub Form_Load()
              Dim cnn As ADODB.Connection
              Dim rst As New ADODB.Recordset

              On Error GoTo ErrHandler

              Set cnn = CurrentProject.Connection
              rst.Open “SELECT * FROM tblMailingLists ORDER BY MailingList”, cnn, adOpenForwardOnly, adLockReadOnly, adCmdText

              Do While Not rst.EOF
              Me.lbxAvailable.AddItem rst!ListID & “;” & rst!MailingList
              rst.MoveNext
              Loop

              ExitHandler:
              On Error Resume Next
              rst.Close
              Set rst = Nothing
              Set cnn = Nothing
              Exit Sub

              ErrHandler:
              MsgBox Err.Description, vbExclamation
              Resume ExitHandler
              End Sub

              See attached demo database.

            • #739069

              Hi Hans

              As usual, thank you so much for your unending time and patience.

              I’ve modified the code, so now it looks like this:

              Private Sub Form_Load()
              Dim cnn As ADODB.Connection
              Dim rst As New ADODB.Recordset

              On Error GoTo ErrHandler

              Set cnn = CurrentProject.Connection
              rst.Open “SELECT list_id, list_name FROM tbl_list_details ORDER BY list_name”, cnn, adOpenForwardOnly, adLockReadOnly, adCmdText

              Do While Not rst.EOF
              Me.lbxAvailable.AddItem rst!list_id & “;” & rst!tbl_list_details
              rst.MoveNext
              Loop

              ExitHandler:
              On Error Resume Next
              rst.Close
              Set rst = Nothing
              Set cnn = Nothing
              Exit Sub

              ErrHandler:
              MsgBox Err.description, vbExclamation
              Resume ExitHandler
              End Sub

              However, when the Form Loads, the following error appears: Item cannot be found in the collection corresponding to the requested name or ordinal.

              I can kind of follow the code, but the error certainly doesn’t seem obvious to me. Can you see what I’ve done wrong? I basically just changed the names of the Object and Fields?

              As always, thanks for your help.

            • #739078

              >> Me.lbxAvailable.AddItem rst!list_id & “;” & rst!tbl_list_details

              rst!tbl_list_details is not correct, since tbl_list_details is the name of the table, not of a field. Replace it by rst!list_name.

            • #739153

              Hans

              You are my HERO!

              That works beautifully!!!!!!

              I just pray that I don’t get those errors at work, but it works flawlessly on my PC.

              P.S. Will “Dim cnn As ADODB.Connection Dim rst As New ADODB.Recordset” still work if I have to upsize the DB to SQL2000? Or is it just a matter of changing to say DAO instead of ADO?

              Anyway, thank you SO, SO MUCH

              I really hope I don’t ever have to bother you again. cheers

              Thanks again, a million times over!!!

            • #739155

              If you upsize to SQL Server, you will move the tables to a SQL Server database, and create links to them in your Access database. The current code should work without modification, as long as the links have the same names as the present tables. You could also create a connection directly to the SQL Server database, in which case the Set cnn = … instruction would have to be modified. There is no particular reason to migrate the code to DAO.

              DAO was the standard data object model in Access up to and including Access 97; it is still available in later versions of Access, and in some situations it is still the best object model to work with, but starting with Access 2000, ADO is the standard object model. DAO is tightly coupled to the Jet Engine that is the core of Access, while ADO is designed to be able to work with a wide variety of data sources.

            • #739537

              Oh right. Got ADO & DAO back-to-front. As Monica just said in Friends “I’m THAT Stupid!”. doh

              [indent]


              You could also create a connection directly to the SQL Server database, in which case the Set cnn = … instruction would have to be modified


              [/indent]. Would there be an advantage to doing this? If I just upsize and point the Access file to the SQL2000 Server DB, then it’ll all be cool, right?

            • #739541

              You should be OK if you just migrate the tables to SQL2000, and create links in your Access database. With a bit of luck, your code will run without batting an eyelash.

            • #739789

              Cool. Thanks for all your help Hans. You have been AWESOME.

              Take care and God Bless

              Brian

            • #739790

              Cool. Thanks for all your help Hans. You have been AWESOME.

              Take care and God Bless

              Brian

            • #739542

              You should be OK if you just migrate the tables to SQL2000, and create links in your Access database. With a bit of luck, your code will run without batting an eyelash.

            • #739538

              Oh right. Got ADO & DAO back-to-front. As Monica just said in Friends “I’m THAT Stupid!”. doh

              [indent]


              You could also create a connection directly to the SQL Server database, in which case the Set cnn = … instruction would have to be modified


              [/indent]. Would there be an advantage to doing this? If I just upsize and point the Access file to the SQL2000 Server DB, then it’ll all be cool, right?

            • #739156

              If you upsize to SQL Server, you will move the tables to a SQL Server database, and create links to them in your Access database. The current code should work without modification, as long as the links have the same names as the present tables. You could also create a connection directly to the SQL Server database, in which case the Set cnn = … instruction would have to be modified. There is no particular reason to migrate the code to DAO.

              DAO was the standard data object model in Access up to and including Access 97; it is still available in later versions of Access, and in some situations it is still the best object model to work with, but starting with Access 2000, ADO is the standard object model. DAO is tightly coupled to the Jet Engine that is the core of Access, while ADO is designed to be able to work with a wide variety of data sources.

            • #739154

              Hans

              You are my HERO!

              That works beautifully!!!!!!

              I just pray that I don’t get those errors at work, but it works flawlessly on my PC.

              P.S. Will “Dim cnn As ADODB.Connection Dim rst As New ADODB.Recordset” still work if I have to upsize the DB to SQL2000? Or is it just a matter of changing to say DAO instead of ADO?

              Anyway, thank you SO, SO MUCH

              I really hope I don’t ever have to bother you again. cheers

              Thanks again, a million times over!!!

            • #739079

              >> Me.lbxAvailable.AddItem rst!list_id & “;” & rst!tbl_list_details

              rst!tbl_list_details is not correct, since tbl_list_details is the name of the table, not of a field. Replace it by rst!list_name.

            • #739070

              Hi Hans

              As usual, thank you so much for your unending time and patience.

              I’ve modified the code, so now it looks like this:

              Private Sub Form_Load()
              Dim cnn As ADODB.Connection
              Dim rst As New ADODB.Recordset

              On Error GoTo ErrHandler

              Set cnn = CurrentProject.Connection
              rst.Open “SELECT list_id, list_name FROM tbl_list_details ORDER BY list_name”, cnn, adOpenForwardOnly, adLockReadOnly, adCmdText

              Do While Not rst.EOF
              Me.lbxAvailable.AddItem rst!list_id & “;” & rst!tbl_list_details
              rst.MoveNext
              Loop

              ExitHandler:
              On Error Resume Next
              rst.Close
              Set rst = Nothing
              Set cnn = Nothing
              Exit Sub

              ErrHandler:
              MsgBox Err.description, vbExclamation
              Resume ExitHandler
              End Sub

              However, when the Form Loads, the following error appears: Item cannot be found in the collection corresponding to the requested name or ordinal.

              I can kind of follow the code, but the error certainly doesn’t seem obvious to me. Can you see what I’ve done wrong? I basically just changed the names of the Object and Fields?

              As always, thanks for your help.

            • #738693

              If you set the Row Source Type property to Value List, the Row Source itself must be a … value list, not the name of a table or query. You must fill the “available” list box when you open the form. Here is demo code for a form with list boxes lbxAvailable and lbxSelected and command buttons cmdAdd and cmdRemove. The table used to populate lbxAvailable is tblMailingList, with two fields: ListID (AutoNumber, primary key) and MailingList (text).

              Here is the code for the form – of course you must adapt it to your situation:

              ‘ On Click event procedure for cmdAdd
              ‘ Moves selected item from lbxAvailable to lbxSelected

              Private Sub cmdAdd_Click()
              If Me.lbxAvailable.ListIndex > -1 Then
              Me.lbxSelected.AddItem Me.lbxAvailable.Column(0) & “;” & Me.lbxAvailable.Column(1)
              Me.lbxAvailable.RemoveItem Me.lbxAvailable.ListIndex
              End If
              End Sub

              ‘ On Click event procedure for cmdRemove
              ‘ Moves selected item from lbxSelected back to lbxAvailable

              Private Sub cmdRemove_Click()
              If Me.lbxSelected.ListIndex > -1 Then
              Me.lbxAvailable.AddItem Me.lbxSelected.Column(0) & “;” & Me.lbxSelected.Column(1)
              Me.lbxSelected.RemoveItem Me.lbxSelected.ListIndex
              End If
              End Sub

              ‘ On Load procedure for form
              ‘ Populates lbxAvailable

              Private Sub Form_Load()
              Dim cnn As ADODB.Connection
              Dim rst As New ADODB.Recordset

              On Error GoTo ErrHandler

              Set cnn = CurrentProject.Connection
              rst.Open “SELECT * FROM tblMailingLists ORDER BY MailingList”, cnn, adOpenForwardOnly, adLockReadOnly, adCmdText

              Do While Not rst.EOF
              Me.lbxAvailable.AddItem rst!ListID & “;” & rst!MailingList
              rst.MoveNext
              Loop

              ExitHandler:
              On Error Resume Next
              rst.Close
              Set rst = Nothing
              Set cnn = Nothing
              Exit Sub

              ErrHandler:
              MsgBox Err.Description, vbExclamation
              Resume ExitHandler
              End Sub

              See attached demo database.

            • #738609

              Thanks Hans! I had forgotten about that thread!

              I changed the Row Source Type to ‘Value List’ and set the Form’s ‘OnLoad’ Event to
              Private Sub Form_Load()
              lbxAvailable.RowSource = “tbl_list_details.list_name”
              End Sub

              . . . in order for it to populate the Available List Box.

              This kinda works in that the value is there in the Available List Box, and I can ‘send’ the item to the Selected List Box, but of course the value shouldn’t read ‘tbl_list_details.list_name”. It should obviously have the name of each List.

              I’ve never ‘populated’ an Item via code, so my attempt to do so is obviously incorrect. Once again, I am forced to ask you for the syntax I would need in order to populate said list.

              I’m sure you’re wishing I had just created multiple Yes/No Fields for each user, huh? flee

            • #738407

              If the export works well on one PC with Office 2003, the problem apparently isn’t caused by the new Office version. I’m afraid I have no idea what else it could be, and there is no way for me to test this.

              You are correct that having a single Yes/No field to indicate which items have been added to the list box on the right will cause problems in a multi-user situation. But creating a separate Yes/No field for each user is going to be a nightmare to maintain – you would have to modify the design of the table and of the form each time the group of users changes. I pointed out some possibilities to make the list boxes work in a multi-user environment in post 282536: either set the Row Source Type to List instead of Table/Query, or use temporary tables in the local front end database.

            • #738405

              Hi Hans

              Thought I’d let you know that I purchased and installed MSOffice 2003 this week, and I’ve tested my Database on the full version, and it works perfectly, so I don’t think there’s a problem with referencing Excel as Excel9.

              However, as stated, I got 2 error messages at work–one per PC, so I’ll try another PC on Monday to see if the code keeps giving me errors. If it does, I don’t know whether you’ll have suggestions or whether I should just try to make do with each user having a separate Check Box that he or she selects in a personalized Query. On that point, I know that one of the reasons you helped me (well, actually, you did virtually everything) was so that I wouldn’t have to rely on check box in a Table, but when I was reviewing the code, I noticed that the ADD and Remove Command Buttons do actually select and deselect a Check Box in a the tbl_List _Details. So, now I’m wondering if this doesn’t defeat the purpose of the complex VBA code you wrote, as the idea was to elimate the need for multiple Yes/No Fields. As it stands, if multiple people were using this Merge feature, the ‘Selected’ Check Box would be selecting and deselting constantly, and the Feature would be unusable?

              Sorry to be a pain–as always, I appreciate your insight and help.

              You truly have the patience of a Saint!

            • #737207

              I thought that the Excel file format hadn’t changed, but I don’t have Office 2003. Perhaps someone with Office 2003 can help here.

            • #737197

              Hi Hans

              I zipped and sent the Database through to my Office today, and–surprisingly–when I clicked the Merge Command Button, something weird happened. It ran the merge, but when I opened the Excel file, the data was all messed up, e.g., the person’s name was in the active column, etc. Surprised, I clicked the Command Button again, but I just got an error message:

              External table is not in the expected format. (Error 3274)
              The format of the table has changed since it was linked. Link the table again, and then retry the operation.

              Both PCs are running Windows XP with Excel 2003 (Beta 2 at home and final Beta at work).

              I’m wondering if the near-gold and gold versions of Access need a new version of Excel stipulated, eg, acSpreadsheetTypeExcel10/11 instead of 9. What do you think?

              I did a few searches on Google, and some people reported some problems between Office 97 and 2000. I’ll–obviously–search further if you’re unsure why this happened, but I just thought you might know off the top of your head. If you don’t, that’s cool. As stated, I’ll ‘google’ it.

            • #737034

              Thank you so much for this great code sample Hans!

            • #705058

              I have attached some sample code. Of course, you must substitute the correct names for the list box, document name etcetera.

            • #705048

              You da man!

    Viewing 0 reply threads
    Reply To: Pass Values from a Form to a Query (XP)

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: