PDA

View Full Version : using loops to search through a text file



almostcool
03-15-2007, 09:31 PM
This is my first post on here so let me say Hello and that I am very new to VBA.

My question is can someone show me a VBA loop that will allow me to use an input box to search through a text file.

I understand that I must use a loop to first read the information in the text file, then possibly a new loop to search through that information.

Thank you.

OBP
03-16-2007, 12:42 PM
Is the text file imported or opened in to Excel, or do you want to read the actual text file?

JimmyTheHand
03-18-2007, 07:13 AM
Hi and welcome to VBAX! :hi:

As OBP implicitly suggested, you might gain more by explaining us what you want to achieve. There are several ways to reach your goal, some of them will be better (i.e. faster, simpler or more elegant) than others. For example, you can read a whole text file into a spreadsheet with one single line of code. Or you can do it with a loop. In a spreadsheet, you can search for a specific string with one single line of code, or you can do it with a loop.

It all depends on what yo really want, and how you want it. If you explain your needs, we can suggest the best solution, or something very close to it.

Regards,
Jimmy

almostcool
03-18-2007, 09:56 AM
What I have is a list of names in a text file.

I need code that allows me to use an input from the user (input box) that uses a loop to search through that text file that is in the same directory.

And then I need to find someway to produce the results of that search in a message box after the user inputs his/her choice in the input box.

I hope this helps. Thanks

mdmackillop
03-18-2007, 10:52 AM
If you could provide a small sample of your text file, what is to be searched and what is to be returned, I'm sure we can come up with a solution. Also, how big a file are we dealing with. A few rows or many thousand.

almostcool
03-18-2007, 04:18 PM
Here is a sample of the text file, it includes a name, birthdate, and fone number.

Example: John Doe, 12/12/12, 555-5555

There is a list of 25 names.

mdmackillop
03-18-2007, 04:44 PM
Option Compare Text
Sub Tel()
Open "G:\TelNos.txt" For Input As #1 ' Open file
ToFind = InputBox("Enter name")
Do While Not EOF(1) ' Check for end of file.
Line Input #1, s ' Read line of data.
'Search for text
If InStr(1, s, ToFind) > 0 Then
'Compose text
msg = msg & s & vbCr
End If
Loop
Close #1
MsgBox msg
End Sub