Use VBA to search text file for string and return line number

对着背影说爱祢 提交于 2020-07-20 03:52:06

问题


I'm trying to search through a txt file for a certain string using a Do While Not EOF loop and then either return or just set a flag of that line number whenever the string is found.

I'm extremely new to VBA with access. What would be the most basic way to go about doing this? I'm using Access 2007

Thank you

Here is what I have so far, I pulled it from various examples online to try to get it to work.

    Dim myFile As String
   Dim text As String
   Dim textline As String
   Dim posIAV As Integer

   myFile = "file path"

   Open myFile For Input As #1

   Do While Not EOF(1)
   Line Input #1, textline
   text = text & textline

   Loop

   Close #1

   posIAV = InStr(text, "IAVs ADDED in this release include")

   MsgBox (posIAV)

回答1:


Just replace MyString below with whatever it is you're looking for.

   Dim myFile As String
   Dim text As String
   Dim textline As String
   Dim posIAV As Integer
   Dim Ctr as Integer
   Dim Ctr2 as Integer

   myFile = "file path"
   Ctr = 0
   Ctr2 = 0

   Open myFile For Input As #1

   Do While Not EOF(1)
   Line Input #1, textline
   text = text & textline

   ' Increment Ctr since you're on the line now
   Ctr = Ctr + 1

   ' Check the current line to see if it contains the string we're looking for
   ' If it does, set Ctr2 to be the current line number
   If textline like "*MyString*" Then
      Ctr2 = Ctr
   End If

   Loop

   Close #1

   posIAV = InStr(text, "IAVs ADDED in this release include")

   MsgBox (posIAV)


来源:https://stackoverflow.com/questions/23369908/use-vba-to-search-text-file-for-string-and-return-line-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!