通过excel搜索txt文件中的字符串列表

时间:2018-03-02 05:12:51

标签: excel-vba text vba excel

我的文件夹中有很多txt文件。我还在第1列中列出了他们的名字,我需要在第2列中列出的每个文件中单独搜索1个字符串。如果找到这样的txt,那么它应该说“找到”或者找不到。

我试图根据我的要求修改下面的代码,但我无法做到,因为它给了我错误,我不知道解决方案。

Sub SearchTextFile()

Dim FName, SName As String

Raise = 2

Do While Raise <> ""
FName = Cells(Raise, 1)
SName = Cells(Raise, 2)

Const strFileName = "Y:\New folder\" & FName & ".txt"
Const strSearch = SName

Dim strLine As String
Dim f As Integer
Dim lngLine As Long
Dim blnFound As Boolean

f = FreeFile

Open strFileName For Input As #f
Do While Not EOF(f)
    lngLine = lngLine + 1
    Line Input #f, strLine
    If InStr(1, strLine, strSearch, vbBinaryCompare) > 0 Then
        Cells(Raise, 3).Value = "Found"
        blnFound = True
        Exit Do
    End If
Loop
Close #f
If Not blnFound Then
    Cells(Raise, 3).Value = "Not Found"
End If

Raise = Raise + 1

Loop

End Sub

1 个答案:

答案 0 :(得分:1)

尝试此修改

Sub Search_Text_Files()
Dim b           As Boolean
Dim sName       As String
Dim sSrch       As String
Dim strFile     As String
Dim sLine       As String
Dim f           As Integer
Dim r           As Long
Dim l           As Long

r = 2

Do While Cells(r, 1) <> ""
    sName = Cells(r, 1)
    sSrch = Cells(r, 2)

    strFile = "Y:\New folder\" & sName & ".txt"
    b = False
    f = FreeFile
    Open strFile For Input As #f

    Do While Not EOF(f)
        l = l + 1
        Line Input #f, sLine
        If InStr(1, sLine, sSrch, vbBinaryCompare) > 0 Then
            Cells(r, 3).Value = "Found"
            b = True: Exit Do
        End If
    Loop

    Close #f
    If Not b Then Cells(r, 3).Value = "Not Found"
    r = r + 1
Loop
End Sub