使用VBA在文本文件中搜索字符串并返回行号

时间:2014-04-29 16:10:54

标签: vba ms-access ms-access-2007 access-vba

我正在尝试使用Do While Not EOF循环搜索某个字符串的txt文件,然后返回或只是在找到该字符串时设置该行号的标志。

我对VBA非常陌生,可以访问。这样做最基本的方法是什么?我正在使用Access 2007

谢谢

这是我到目前为止所做的,我从网上各种例子中提取它,试图让它发挥作用。

    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 个答案:

答案 0 :(得分:1)

只需将下面的 MyString 替换为您正在寻找的任何内容。

   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)