excel - 读取特定字符串的文本文件,如果找不到则打开 msgbox
问题描述
如何打开文本文件并查找特定字符串?
我希望字符串“productactivated=true”确定是否在用户窗体上显示一条消息,告诉用户激活。
几天前,我请求帮助打开一个文本文件并进行一些阅读和写作,所以我想出了这个
Open "application.txt" For Output As #1
ClngLine = lngLine + 1
Line Input #f, strLine
If InStr(1, strLine, strSearch, vbBinaryCompare) > 0 Then
MsgBox "Search string found in line " & lngLine, vbInformation
blnFound = True
Close #1
解决方案
对于您的解决方案,将使用两个文件来展示如何读取和写入文本文件。添加文字只是为了向您展示如何操作,但根据您的问题陈述,您的解决方案似乎不需要。出于此解决方案的目的,所有文件都位于同一文件夹中。
第一个文件是正在读取的文件。出于演示目的,由于未提供数据,因此使用以下数据创建并命名为“ TextFile.txt ”:
This is the first line.
This is the second line and has productactivated=true.
Third line lays here.
productactivated=true is found in line four.
第二个文件是要写入的文件。出于演示目的,只是为了展示它是如何完成的,但不需要根据您的问题,并命名为“ TextFile.txt ”:
This is the first line.
This is the second line and has productactivated=true.
Third line lays here.
productactivated=true is found in line four.
VBA代码:
Sub search_file()
Const ForReading = 1, ForWriting = 2
Dim FSO, FileIn, FileOut, strSearch, strTmp
'FileSystemObject also called as FSO, provides an easy object based model to access computer’s file system.
Set FSO = CreateObject("Scripting.FileSystemObject")
'Set FileIn to the file for reading the text into the program.
Set FileIn = FSO.OpenTextFile("TextFile.txt", ForReading)
'Set FileOut to the file for writing the text out from the program.
'This was added just to show "how to" write to a file.
Set FileOut = FSO.OpenTextFile("TextFileRecordsFound.txt", ForWriting, True)
'Set the variable to the string of text you are looking for in the file you are reading into the program.
strSearch = "productactivated=true"
'Do this code until you reach the end of the file.
Do Until FileIn.AtEndOfStream
'Store the current line of text to search to work with into the variable.
strTmp = FileIn.ReadLine
'Determines whether to display a message
'(Find out if the search text is in the line of text read in from the file.)
If InStr(1, strTmp, strSearch, vbTextCompare) > 0 Then
'Display a message telling the user to activate.
MsgBox strSearch & " was found in the line:" & vbNewLine & vbNewLine & strTmp, , "Activate"
'Write the line of text to an external file, just to demo how to.
FileOut.WriteLine strTmp
End If
Loop 'Repeat code inside Do Loop.
'Close files.
FileIn.Close
FileOut.Close
End Sub
推荐阅读
- javascript - $(window).on('load', ...) 在 MS Edge 中发生得太快
- git - 如果拉取请求未合并并且上游/主进程推进,那么理想的 git 工作流程应该是什么
- primefaces - 如何仅在包含特定值时才禁用列的编辑?
- java - 我的程序有没有办法接受短语并以猪拉丁语输出它们?
- python - 从 txt 文件中删除标题的 Python 代码
- javascript - jQuery 导航和发布 JSON
- tensorflow - 如何在强化学习期间使用带有渐变的 Keras Tensorboard 回调?
- asp.net - 如何在 Asp.Net MVC 5 上使用实体框架 6 将图像(图像路径/二进制)添加到数据库?
- apache-spark - How to use helm chart for spark on k8s
- windows - 无法通过 localhost 访问在 Docker 上运行的 Kurento 媒体服务器