我的文件夹中有很多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
结束子
试试这个修改
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