How to Populate Combo Box Access VBA

889 views Asked by At

I am trying to fill in a combo box with names from a text file. The file ill ready something to the affect of.

Greg Smith
John Oliver
Bob Cassidy
....
....

So far I have the code from another thread which works great but only takes the last name from the list and the other names are no where to be found. The code is:

Dim MyStr1 as string
dim MyStr2 as string

Open "TESTFILE" For Input As #1
Do While Not EOF(1) ' Loop until end of file.
Input #1, MyStr1, MyStr2
me.txtStr1 = MyStr1
me.txtStr2 = MyStr2
Loop
Close #1 ' Close file.

Any help would be greatly appreciated.

1

There are 1 answers

3
DevBW On

Assuming you're just trying to populate one combo box with a list of first and last names (where the names are separated by a line break), try this:

Dim filePath As String
Dim oFSO As New FileSystemObject
Dim oFS As TextStream

filePath = "C:\FileFullOfNames.txt"

Set oFS = oFSO.OpenTextFile(filePath)

Do While Not oFS.AtEndOfStream
  MyForm.ComboBox1.AddItem oFS.ReadLine
Loop

oFS.Close

Set oFS = Nothing

If you've never used FileSystemObject & TextStream, you'll need to add the Microsoft Scripting Runtime reference in your VBE. (Tools > References > Check the box labeled "Microsoft Scripting Runtime").