首页 > 解决方案 > 读取特定字符串的文本文件,如果找不到则打开 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

标签: excelvba

解决方案


对于您的解决方案,将使用两个文件来展示如何读取和写入文本文件。添加文字只是为了向您展示如何操作,但根据您的问题陈述,您的解决方案似乎不需要。出于此解决方案的目的,所有文件都位于同一文件夹中。

第一个文件是正在读取的文件。出于演示目的,由于未提供数据,因此使用以下数据创建并命名为“ 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

msgbox 截图


推荐阅读