Hi Torstein
I want to make a userform where the user can write one or more letters in a
field. I want the combo-box tol be filled (is that the same as populated?)
with all subdir that starts with that letter(s). From that combobox the user
can choose one directory and then the fileopen dialog is opened.
Here's one way to do it (only roughly outlined):
Consider a UserForm with a Textbox "txtQuickfinder" and a Listbox
"lbxDirectories". The former will be used to fill in the starting letters,
the latter will contain the list of matching listboxes. Write a routine,
which gathers all directories matching a given string and adds them
to the listbox ("PopulateList"), e.g.:
Private Sub PopulateListbox(lbx As ListBox, Optional filter As String = "*")
' Note that you should NEVER hardcode paths! this is just for quick'n'dirty
demonstration!!!
Const FLDR = "D:\Programme"
Dim directory As String
' clear the listbox of previously added directories
lbx.Clear
' get first file
directory = Dir(FLDR & "\*", vbDirectory)
Do
' stop if no more file found
If directory = "" Then Exit Do
' this is the tricky part: check if it is a directory, and compare
the
' current directory's name to the given filter pattern
If isDir(FLDR, directory) And (LCase(directory) Like LCase(filter))
Then
lbx.AddItem directory
End If
directory = Dir()
Loop
End Sub
Note that the Dir-function always returns files as well, so don't forget to
check if it really is a directory (line 15). The helper function to check
if a found item is a directory might look something like this:
Function isDir(path As String, name As String) As Boolean
' check if it is a directory
isDir = (GetAttr(path & "\" & name) And vbDirectory)
' check if it is not the . (active dir) or .. ("super" dir)
isDir = isDir And name <> "." And name <> ".."
End Function
That's all you need. Now for the UserForm: Let the listbox be
populated with all subdirs whenever the UserForm ist started
(Initialize-event-handler):
Private Sub UserForm_Initialize()
Call PopulateListbox(Me.lbxDirectories)
End Sub
Now the only thing left to do is to react to the Change-event of
the textbox:
Private Sub txtQuickfinder_Change()
Call PopulateListbox(Me.lbxDirectories, Me.txtQuickfinder.text & "*")
End Sub
Done! Not that difficult, was it? There are, however, various things to
consider:
- The list of directories comes unsorted. In a more sophisiticated version,
you might want to read the dirs into an array and sort it before adding
the items to the listbox.
- All the directories are read in every time the user writes a letter into
the
quickfinder-textbox. If you have hundreds of subdirs or if you are
working with network drives, things might run very slowly.
Ok, that's it for the moment. Have fun playing around with the code
Cheers,
Martin