View Single Post
 
Old 11-22-2013, 12:56 PM
BobBridges's Avatar
BobBridges BobBridges is offline Windows 7 64bit Office 2010 32bit
Expert
 
Join Date: May 2013
Location: USA
Posts: 700
BobBridges has a spectacular aura aboutBobBridges has a spectacular aura about
Default

Out of habit, for I/O in VB I use the FileSystemObject rather than the native Basic statements for I/O—the Open, Input and Close statements, I mean [see footnote]. But judging by your results, what you've done so far will work fine, so unless you decide you want to switch to the fso, let's go with what you have so far. Let's start with your program as it is so far:
Code:
Open Fname For Input As #1
jr = 0
Do While Not EOF(1)
  Input #1, A
  jr = jr + 1
  If A = "1990" Then MsgBox jr
  Loop
Close 1
I changed one of the variable names because of my own prejudices, but the basic structure is the same. Now for your question: There are always more than two ways to skin a cat, in programming, but here are the two obvious ways that come to me immediately. First, you could run two different loops:
Code:
Open Fname For Input As #1

' First find the starting statement.
Do While Not EOF(1)
  Input #1, A
  If A = "1990" Then Exit Do
  Loop
If EOF(1) then Exit Sub ' "1990" did not appear

' Now handle the subsequent data.
Do While Not EOF(1)
  Input #1, A
  ' insert statements here to put the value of A into various cells.
  Loop
Close 1
There's nothing wrong with this method, but sometimes I like to use a switch instead; until we've run into the starting trigger ("1990", I mean) the switch is off, and after that it's on again. This allows us to use the same loop, if you like that idea:
Code:
Open Fname For Input As #1
fData = False
Do While Not EOF(1)
  Input #1, A
  If fData Then
    ' insert statements here to put the value of A into various cells.
  ElseIf A = "1990" Then
    fData = True
    End If
  Loop
Close 1
In this version, fData starts as False, but as soon as you run into "1900" the program changes it to True. Whenever fData is True, the program executes your statements to copy the data to your worksheet; the rest of the time it just checks to see whether "1900" has appeared yet.

None of the above takes into account the ending trigger; I expect you can work that out yourself, given the above hints. But feel free to ask further if you need more help.

---

[footnote:] The FileSystemObject gives you a lot of control over your PC's drives, folders and files. But the differences in this logic are pretty minor. Here's your program, as I would have written it:
Code:
Open Fname For Input As #1
jr = 0
Do While Not EOF(1)
  Input #1, A
  jr = jr + 1
  If A = "1990" Then MsgBox jr
  Loop
Close 1
If you're curious, the equivalent using the fso would look like this:
Code:
Set fo = fso.OpenTextFile(Fname, 1) 'ForReading
jr = 0
Do While Not fo.AtEndOfStream
  A = fo.ReadLine
  jr = jr + 1
  If A = "1990" Then MsgBox jr
  Loop
fo.Close
Reply With Quote