Text too wide for a ListBox or ComboBox entry

Article contributed by Jonathan West

If the text you need to fit into an entry of a ListBox (or a ComboBox) is wider than the ListBox itself, then you find that the end of the string is hidden, and you simply can't see it. This can be something of a nuisance. For instance, if you have a list of files, including their full paths, then you really do want to see the filename on the end of the string! There isn't a MultiLine property for ListBox entries, so you can't get the string to wrap onto a second line, the way you can in a label or TextBox.

There are two solutions available.

1.

Set up a horizontal scrollbar for the ListBox

This is simple, though not obvious. There is no ScrollBar property in a ListBox, nor anything that looks remotely like one. Nonetheless, you can get a horizontal scrollbar. All you have to do is to set the ColumnWidths property of the ListBox to be larger than the Width property. If you have a multi-column ListBox, then you need to ensure that the sum of the column widths is larger than the Width property.

2.

Trim the text

This is specific to putting pathnames into a ListBox. You will see, in many places in Word, that filenames get shortened to fit the available space, by putting an ellipsis (...) into the middle of the path name. The following code allows you to do the same.

You pass a path name to the PathName parameter, and the maximum length in characters of the truncated path to the PathLength parameter.

If the original pathname is less than the maximum length, then it is returned by the function. If it is shorter than the maximum length, then the function takes out one or more of the folder names of the path and replaces them with an ellipsis.

If the required length is very short, then the function will return just the first element (usually the drive letter) and the filename. The code below requires Word 2000 or later to run, as it uses the Split function, which is not available in Word 97.

Public Function EllipsisPathName(PathName As String, PathLength As Long)

Dim vPath As Variant
Dim iLastFolder As Long
Dim iCurrentLength As Long
Dim iUsedFolder As Long
Dim strEllipsePath As String

If PathLength >= Len(PathName) Then
    EllipsePathName = PathName
    Exit Function
End If

iCurrentLength = Len(PathName) + 4
vPath = Split(PathName, "\")

For iLastFolder = UBound(vPath) - 1 To 1 Step -1
    iCurrentLength = iCurrentLength - Len(vPath(iLastFolder)) - 1

    If iCurrentLength <= PathLength Then
        For iUsedFolder = 0 To iLastFolder - 1
            strEllipsePath = strEllipsePath & vPath(iUsedFolder) & "\"
        Next iUsedFolder

        strEllipsePath = strEllipsePath & "...\" & vPath(UBound(vPath))
        EllipsisPathName = strEllipsePath
        Exit Function
    End If
Next iLastFolder

EllipsisPathName = vPath(0) & "\...\" & vPath(UBound(vPath))

End Function