使用 VBA 在文本文件中搜索字符串并返回行号 [英] Use VBA to search text file for string and return line number

查看:800
本文介绍了使用 VBA 在文本文件中搜索字符串并返回行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我对具有访问权限的 VBA 非常陌生.这样做的最基本方法是什么?我正在使用 Access 2007

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

谢谢

这是我目前所拥有的,我从网上的各种示例中提取出来,试图让它发挥作用.

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)

推荐答案

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

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)

这篇关于使用 VBA 在文本文件中搜索字符串并返回行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆