VBA:从文本文件中读取特定的字符串,然后如果未找到则打开msgbox

时间:2018-12-22 21:42:20

标签: excel vba

晚上好

今天,我一直在尝试找出如何在VBA中打开文本文件,并查找特定的字符串。我需要这样做,以便如果字符串:

'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

如果有人知道如何解决此问题,我将不胜感激

欢呼

1 个答案:

答案 0 :(得分:3)

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

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

screenshot of msgbox