Hi James, thanks for your timely reply. Here's the code:
In the Click Event of the "Add" button on the form:
Dim intIndexLongestText As Integer
Dim sngnVar As Single
Me.ScaleMode = vbPixels
lstScroll.AddItem txtText.Text
For mintCount = 1 To lstScroll.ListCount
sngnVar = Me.TextWidth(lstScroll.List(mintCount - 1))
If (sngnVar + 6) > lstScroll.Width Then
intIndexLongestText = (mintCount - 1)
SetHScroll Me, lstScroll, lstScroll.List(intIndexLongestText)
Exit For
End If
Next mintCount
txtText.Text = ""
Code in a Standard Code Module:
Option Explicit
Public Const LB_SETHORIZONTALEXTENT = &H194
Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long
Public Sub SetHScroll(Frm As Form, Ctrl As Control, strText As String)
Dim nScaleMode As Integer
Dim nTextWidth As Integer
nScaleMode = Frm.ScaleMode
Frm.ScaleMode = 3 'vbPixels
nTextWidth = (Frm.TextWidth(strText) + 6)
SendMessage Ctrl.hWnd, LB_SETHORIZONTALEXTENT, nTextWidth, 0
Frm.ScaleMode = nScaleMode
End Sub
Since I wrote this code, I discovered a bug in it, in that if you add another item to the list box whose textwidth is greater than the width of the listbox (both in terms of pixels), but shorter than that of the item which initially caused the scrollbar to appear, the scrollbar resizes itself to fit the shorter "long item". Thus, the original "long item" gets cut off. I have since come to realize that this code works by knowing the list index of the longest item in the list at all times, so that the scrollbar can size itself accordingly if and when it is needed. I believe this can be achieved using nested For......Next Loops, which I'm currently working on. However, once that problem is solved, I am still at a loss to find a way to make the scrollbar disappear, when you remove all the items from the list which are longer than the width of the listbox. Hope you can offer some insight into how to accomplish this.
Thanks,
Bud
Enter your message below
Sign in or Join us (it's free).