.Additem problem (1 Viewer)

kirkm

Registered User.
Local time
Tomorrow, 09:13
Joined
Oct 30, 2008
Messages
1,257
Run into a bit of a snag addressing a Form.
My code is in a module and I want to add items to a Listbox.

With Form_Form1.Form.List1
.AddItem "1234"

With forms("Form1").Form!List1
Most examples use "Me" but that's no good in a module, is it ?
Everything I try brings up an error. Can you set me straight ?
 

MajP

You've got your good things, and you've got mine.
Local time
Today, 17:13
Joined
May 21, 2018
Messages
8,527
if this code is being called from the form's module you can simply do
me.List1.addItem
or even
List1.addItem

All controls are properties of the form so you can call them directly.
Make sure you set the rowsource type to "value list" in the listbox properties.
 
Last edited:

arnelgp

..forever waiting... waiting for jellybean!
Local time
Tomorrow, 05:13
Joined
May 7, 2009
Messages
19,237
create a public Sub/Function:
Code:
Public Sub ListAddItem(ByRef Lst As Object, itm As Variant)
    With Lst
        If TypeOf Lst Is ListBox Or TypeOf Lst Is ComboBox Then
            If .RowSourceType = "Value List" Then
                .AddItem itm
            End If
        End If
    End With
End Sub

on your code

Call ListAddItem([yourListbox/combobox], "item to add")
 

kirkm

Registered User.
Local time
Tomorrow, 09:13
Joined
Oct 30, 2008
Messages
1,257
This is a standard Module, not a Form Module. I did get something sort of working but must have committed some major sin because if the Remmed ELSE line is unremmed, Access aborts and shuts down without warning.
Code:
Function zComments(Mode, Comm) As String 
        If Nz(Comm) > "" Then
                Dim item As Variant
                Dim Dat As Variant
                Comm = WrapToFit(CStr(Comm), 0)
                With Forms!Form1.Form.lstBComm
                    .RowSource = ""
                    Dat = Split(Comm, vbLf)
                    For Each item In Dat
                        .AddItem item
                    Next
                End With
            Else
               ' Forms!Form1.Form.lstBComm.RowSource = ""
        End If
End Function
I guess this means .RowSource= "" isn't allowed in Comm is "". Maybe I can Remove All some other way.
The function isn't returning anything (yet) as it's being tweaked still.
But all else being ok Forms!Form1.Form.lstBComm would be correct ?
 

MajP

You've got your good things, and you've got mine.
Local time
Today, 17:13
Joined
May 21, 2018
Messages
8,527
Did you make that up yourself, or did you copy it from somewhere? It is really whacky. Does not make much sense, unless there is some complex reason for this.
1. Mode argument is not used but required
2. The function is written as if it returns a string (for what purpose) but does not anyways
3. Comm is a string with items separated by a linefeed? Not sure how you even do that
4. What is the wraptofit function and what is its purpose.
You wrote this as a function but why since the listbox is not an argument it is hardwired to one listbox.
Unless there is some reason for this, it is crazy overly complicated. What are you really trying to do?
 

kirkm

Registered User.
Local time
Tomorrow, 09:13
Joined
Oct 30, 2008
Messages
1,257
LOL it is not whacky and yes it's all mine! I did say it was being tweaked, as in still being developed and I'm getting it working in stages. Hence the unused variable 'Mode' and the function not returning anything.
WrappedtoFit turns text into multi lines so each will fit in a listbox row. I don't think Access has any inbuilt function to do that. Be nice if I'm wrong though. The Source data (Comm) is vblf delimited. What's so odd about that?
The functions task is to populate a list box. I would really like to know why you think ir's whacky Maj ? I appreciate you replying but did ignore my main question? Since then I've found
While .ListCount > 0
.RemoveItem (0)
Wend
works. But the one liner would be better.
This forum can be a hard case place to get anywhere with, unfortunately I don't have any other source of info or help, other that Google where you can't home in a specific issue too readily.
 

MajP

You've got your good things, and you've got mine.
Local time
Today, 17:13
Joined
May 21, 2018
Messages
8,527
LOL it is not whacky and yes it's all mine!
When you provide partial information it appears real whacky. I listed 5 good reasons why to an outsider this make no sense, if you provide some information "why" that could have helped.

Maybe something more like.
Code:
Public Function zComments(Mode As Variant, Comm As Variant, lst As Access.ListBox) As String
    'mode not included in code yet. To be developed.
    Dim Dat() As String ' split works on a string
    Dim i As Integer
   
    clearlist lst
    If Not IsNull(Comm) Then
       Comm = WrapToFit(CStr(Comm), 0) 'returns a string with vblf to seperate
       Dat = Split(Comm, vbLf)
       For i = 0 To UBound(Dat)
          lst.AddItem Dat(i)
       Next i
    End If
    zComments = "There are " & i & " items added"
End Function

Public Sub ClearList(lst As Access.listbox)
  Dim i As Integer
  If lst.RowSourceType = "value list" Then
    For i = lst.ListCount - 1 To 0 Step -1
      lst.RemoveItem (i)
    Next i
  Else
    lst.RowSource = ""
  End If
End Sub
 
Last edited:

MajP

You've got your good things, and you've got mine.
Local time
Today, 17:13
Joined
May 21, 2018
Messages
8,527
Not sure why anyone would do it, but this takes a long string and fits it into a listbox by fitting fitting as much text in per line. It uses the hidden winhooks function to determine the length of a string based on the font. I gave you the option to split on a word or split anywhere.
Code:
Public Function LoadWrapList(lst As Access.listbox, longString As Variant, Optional PK As Variant = 0, Optional wholeWords = True) As String
  Dim visWidth As Long
  Dim visWidthInches As Long
  Dim arr() As String
  Dim I As Integer
  Dim txt As String
  Dim txtLength As Long
  Const buffer = 40
 
  'I think this makes sense only with one visible column little more complicated if not
  lst.RowSourceType = "Value List"
  visWidth = lst.Width - buffer
  lst.ColumnCount = 2
  lst.ColumnWidths = "0;" & visWidth / 1440 & " in"
  ClearList lst
   If Not IsNull(longString) Then
    longString = Replace(longString, ",", "")
    If wholeWords Then
      arr = Split(longString, " ")
      For I = 0 To UBound(arr)
        If txt = "" Then
          txt = txt & Trim(arr(I))
        Else
          txt = txt & " " & Trim(arr(I))
        End If
        txtLength = GetTextLength(lst, txt)
        If GetTextLength(lst, arr(I)) > visWidth Then
          MsgBox "Whole words are greater than visible length. Exiting", vbInformation
          Exit Function
        End If
        If txtLength >= visWidth Or arr(I) = vbCrLf Then
           If txtLength > visWidth Or arr(I) = vbCrLf Then
             ' roll back
            
             txt = Left(txt, Len(txt) - Len(arr(I)))
             If I > 0 Then I = I - 1
            End If
            'Debug.Print PK & "; " & txt
            lst.AddItem PK & "; " & Trim(txt)
           txt = ""
         End If
      Next I
      If txt <> "" Then lst.AddItem PK & "; " & Trim(txt)
    Else
        For I = 1 To Len(longString)
         txt = txt & Mid(longString, I, 1)
         'Debug.Print txt
         txtLength = GetTextLength(lst, txt)
         If txtLength >= visWidth Then
           If txtLength > visWidth Then
             ' roll back
             txt = Left(txt, Len(txt) - 1)
             I = I - 1
            End If
            'Debug.Print PK & "; " & txt
            lst.AddItem PK & "; " & txt
           txt = ""
         End If
        Next I
    End If
  End If
End Function

Public Function GetTextLength(pCtrl As Control, ByVal str As String, _
                              Optional ByVal Height As Boolean = False)
    Dim lx As Long, ly As Long
    ' Initialize WizHook
    WizHook.Key = 51488399
    ' Populate the variables lx and ly with the width and height of the
    ' string in twips, according to the font settings of the control
    WizHook.TwipsFromFont pCtrl.FontName, pCtrl.FontSize, pCtrl.FontWeight, _
                          pCtrl.FontItalic, pCtrl.FontUnderline, 0, _
                          str, 0, lx, ly
    If Not Height Then
        GetTextLength = Abs(lx)
    Else
        GetTextLength = Abs(ly)
    End If
End Function
Public Sub ClearList(lst As Access.listbox)
  Dim I As Integer
  If lst.RowSourceType = "value list" Then
    For I = lst.ListCount - 1 To 0 Step -1
      lst.RemoveItem (I)
    Next I
  Else
    lst.RowSource = ""
  End If
End Sub

listwrap.png

The left is the long text, the right is a listbox breaking it up to several lines and splitting on whole words.
Not sure how you would use that.
 

Attachments

  • WordWrapListbox.accdb
    4.1 MB · Views: 117

kirkm

Registered User.
Local time
Tomorrow, 09:13
Joined
Oct 30, 2008
Messages
1,257
Maj I am readying a demo for you in a seperate thread and this is very much a part of it. You will explain all and show how this issue's been tackled. It wasn't easy, isn't good, but 99% works. You may well have nailed it and I can replace all my stuff with yours ? It may take me ah hour or so so to finish. Thank you.
 

MajP

You've got your good things, and you've got mine.
Local time
Today, 17:13
Joined
May 21, 2018
Messages
8,527
Sounds good. I am curious to see how this would be used.
 

Pat Hartman

Super Moderator
Staff member
Local time
Today, 17:13
Joined
Feb 19, 2002
Messages
43,266
Looks pretty useless to me. Each line in a list box is expected to be a "record" AND have a unique ID. The sample only ever shows only ONE item in the listbox Plus, the listbox isn't bound so it is essentially inert. Just because each line will highlight, doesn't mean you can bind the listbox to a field.

I can understand why you might want to do this for a textbox to make it look better but a listbox? I also can't wait to find out why.

Usually when people have blocks of text they want to select from a listbox/combo, they have a short version and a long version. that way they can show the short version but copy the long version into a textbox. I've done this a couple of times when the user wants canned text for ease of data entry but wants to be able to customize it so the combo/listbox is never bound. It is just used save typing. The click event just copies text into a bound textbox.
 

kirkm

Registered User.
Local time
Tomorrow, 09:13
Joined
Oct 30, 2008
Messages
1,257
I seem to have struck a number of unresolvable problems... even after 3 hours trying to fix them. Queries that don't run all the time - or rather, fail to go to a function they should. Text boxes that just show #Deleted.
A situation where Access just closes (I've remmed this out to see why later).
Should I upload it with these problems. It actually runs, but is fragile. Once I gave up, closed it, and when I opened it next it worked.
 

kirkm

Registered User.
Local time
Tomorrow, 09:13
Joined
Oct 30, 2008
Messages
1,257
This is probably reasonable to show what I'm attempting. It won't clear the listbox at the moment (I don't know why).
Form1 runs it.
 

Attachments

  • ListboxProblem2.zip
    822.6 KB · Views: 125

MajP

You've got your good things, and you've got mine.
Local time
Today, 17:13
Joined
May 21, 2018
Messages
8,527
The sample only ever shows only ONE item in the listbox Plus, the listbox isn't bound so it is essentially inert. Just because each line will highlight, doesn't mean you can bind the listbox to a field.
Actually as crazy as it seems you can definitely bind this control, I designed it that way. This assumes you are storing the PK for the string.
I am not saying I would ever do it, but it is more feasible than i thought. Each line holds the same PK to the record so you can click on any line and bind the 1st hidden column.
multiValue.jpg
 

Attachments

  • WordWrapListbox2.accdb
    4.1 MB · Views: 112

MajP

You've got your good things, and you've got mine.
Local time
Today, 17:13
Joined
May 21, 2018
Messages
8,527
I do not get how this is supposed to work. I would assume in the details section if I click on "The King and I", I would be able to load those tracks in the listbox. There is no key relating tblListA tracks to an album. There is no ID on the tracks either. I am clueless of what this does. You will have to explain what you expect to see in the listbox.
 

MajP

You've got your good things, and you've got mine.
Local time
Today, 17:13
Joined
May 21, 2018
Messages
8,527
Assume my table looked like this. I have no idea what the original table was supposed to be. But in this table there are long fields. None are split ahead of time.
tblListA tblListA

datIDDatalbumID_FK
72​
A1. Orchestra conducted by Jay Blackton – Overture 4:52
2728​
73​
A2. Gordon MacRae – Oh, What a Beautiful Mornin' 2:36
2728​
74​
A3. Gordon MacRae, Shirley Jones, Charlotte Greenwood – The Surrey With the Fringe on Top 4:53
2728​
76​
A4. Gene Nelson, Charlotte Greenwood, Men's Chorus – Kansas City 2:36
2728​
77​
A5. Gloria Grahame – I Cain't Say No 3:10
2728​
78​
A6. Shirley Jones & Girls' Chorus – Many a New Day 3:09
2728​
79​
B1. Gordon MacRae & Shirley Jones – People Will Say We're in Love 4:21
2728​
80​
B2. Gordon MacRae & Rod Steiger – Pore Jud is Daid 4:16
2728​
81​
B3. Shirley Jones – Out of My Dreams 2:25
2728​
82​
B4. Gordon MacRae, Charlotte Greenwood, Gene Nelson, Jay C. Flippen, James Whitmore, Gloria Grahame, Mixed Chorus – The Farmer And The Cowman 2:58
2728​
84​
B5. Gloria Grahame & Gene Nelson – All Er Nothin' 2:59
2728​
85​
B6. Gordon MacRae, Charlotte Greenwood, James Whitmore, Shirley Jones, Jay C. Flippen, Mixed Chorus – Oklahoma! 3:18
2728​
Then using this code
Code:
Private Sub Form_Current()
  Dim rs As DAO.Recordset
  Dim strSql As String
  strSql = "Select * from tblListA where AlbumID_FK = " & Nz(Me.id, 0)
  Set rs = CurrentDb.OpenRecordset(strSql)
  ClearList Me.lstAComm
  Do While Not rs.EOF
    LoadWrapList Me.lstAComm, rs!Dat, rs!datid
    rs.MoveNext
  Loop
End Sub
I would get this
listwrap2.jpg
 

Attachments

  • ListboxWrap.zip
    817.4 KB · Views: 154

kirkm

Registered User.
Local time
Tomorrow, 09:13
Joined
Oct 30, 2008
Messages
1,257
I think you have what's wanted exactly Maj. What your listbox shows is it.
That is all it does at this point, just copy the details into the listbox without truncating ot losing any of the data.
Not sure whats meant by no Key or ID ? Some necessary step I didn't do ? The ID I used was the prefix field. Just about tosee your latest file, so that may show but I'll be curious how you cleared tblListA each time a record is clicked. That was a problem here, Access wouldn't do that without putitng #Deleted in the list box. Yet the table should have been updated and the listboc show the new data.
 

kirkm

Registered User.
Local time
Tomorrow, 09:13
Joined
Oct 30, 2008
Messages
1,257
Opening Form1 in MajpListBoxProblem2 populates the List box with Numbers. If I run your Form_Current event it complains about Me.id.
Is something missing ?
The table now has contains all albums. My plan was for it to contain just the required one album, then pass each record through the wordwrap routine and populate the list.
What next? I'm tempted to abort attempts to do it an "Access Way" and go back to doing it my way.
Your routine to wrap lines, OK to use that ?
 

MajP

You've got your good things, and you've got mine.
Local time
Today, 17:13
Joined
May 21, 2018
Messages
8,527
Opening Form1 in MajpListBoxProblem2 populates the List box with Numbers. If I run your Form_Current event it complains about Me.id.
Is something missing ?
Sorry. I was not demoing that form. I have no idea what that is supposed to do. My demo was in form3. You scroll through the albums and see the related tracks.
Not sure whats meant by no Key or ID ?
Every database table MUST have a primary key and if it is related to another table it has a foreign key. How are you relating tracks to albums. There are lots of examples on this forum of well formatted music libraries. Some examples mentioned in this thread
 

kirkm

Registered User.
Local time
Tomorrow, 09:13
Joined
Oct 30, 2008
Messages
1,257
Hey, very nice! I'm not sure how I missed the new stufff you'd added, but have caught up now. I will try incorparating your wrapping routine, it's certainly much more concise than I had. You set list colums to 2, the first may have a width of 0. Not sure why that might be yet. A part of the code exits if lst, arr(I)) > visWidth. I doubt this would ever happen but could a space be inserted/used so it can't happen ?

My db is not relational. Everything is in one table so I've no need for P or F keys, and their complications. One table is so easy to update and maintain. You asked How are you relating tracks to albums. There's no relationship, the tarcks *are* the album.
So yes, this may be different to what is conventional, but will be better for us than any "nicely Formatted" music database as it's features are purpose built. Last few days have been rough as I veered into the unknown and shouldn't have. Struggling with that (and a bug just found) was a bit much for the brain. I'm not a trained Access programmer, but enjoy making things work.
Many thanks for taking a look - and the new wrap routine. I wasn't sure if what I had was perfect, as hadn't got far enough to do major testing.
 

Users who are viewing this thread

Top Bottom