Add information to an Excel file - excel

I've made a VBA macro that allows me to get information from a specific file from a folder.
The format of the name is Name_Timestamp.extension
I get the TimeStamp.
What I need to do: add the Name file in column G, the time stamp in column B and a word in column J to an Excel with headers.
Do you have any Idea on how I can do it ?
Dim Chemin As String, Fichier As String, timeStamp As String
'Définit le répertoire contenant les fichiers
Chemin = "PATH"
Fichier = Dir(Chemin & "*.*")
timeStamp = Split(Fichier, "_")(2)
timeStamp = Split(timeStamp, ".")(0)
Do While Len(Fichier) > 0
MsgBox (Fichier & "___" & timeStamp)
Fichier = Dir
Loop
End Sub

Split by Timestamp
Adjust the values in the constants section.
The Code
Option Explicit
Sub splitByTimeStamp()
Const wsName As String = "Sheet1"
Const FirstRow As Long = 2
Const FolderPath As String = "C:\Test"
Const aWord As String = "a word"
Const TimeStampDelimiter As String = "_" ' don't use a dot ('.').
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
Dim pSep As String: pSep = Application.PathSeparator
Dim FileName As String: FileName = Dir(FolderPath & pSep & "*.*")
Dim cRow As Long: cRow = FirstRow
Dim sArr() As String
Dim cString As String
Dim NoStamp As String
Dim TimeStamp As String
Dim n As Long
Application.ScreenUpdating = False
Do While Len(FileName) > 0
sArr = Split(FileName, TimeStampDelimiter)
Select Case UBound(sArr)
Case 0
cString = sArr(0)
NoStamp = Left(cString, InStrRev(cString, ".") - 1)
TimeStamp = ""
Case 1
NoStamp = sArr(0)
cString = sArr(1)
TimeStamp = Left(cString, InStrRev(cString, ".") - 1)
Case Else
For n = 0 To UBound(sArr) - 1
NoStamp = NoStamp & sArr(n) & TimeStampDelimiter
Next n
NoStamp = Left(NoStamp, Len(NoStamp) - Len(TimeStampDelimiter))
cString = sArr(UBound(sArr))
TimeStamp = Left(cString, InStrRev(cString, ".") - 1)
End Select
ws.Cells(cRow, "B").Value = TimeStamp
ws.Cells(cRow, "G").Value = NoStamp
ws.Cells(cRow, "J").Value = aWord
cRow = cRow + 1
FileName = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Files Found: " & cRow - FirstRow, vbInformation, "Success"
End Sub

Related

Counter to increment variable value

I'm trying to name sheets based on the current date. I need a counter variable to name sheets so they're unique.
I made two attempts:
Sub COPIAR_MODELO()
Application.ScreenUpdating = False
Dim i As Integer, x As Integer
Dim shtname As String
Dim WSDummy As Worksheet
Dim TxtError As String
Dim counter As Long
counter = 0
Name01:
For counter = 1 To 100 Step 0
TxtError = ""
counter = counter + 1
shtname = Format(Now(), "dd mm yyyy") & " - " & counter
On Error Resume Next
Set WSDummy = Sheets(shtname)
If Not (WSDummy Is Nothing) Then TxtError = "Name taken, additional sheet added!"
Next counter
If TxtError <> "" Then MsgBox "" & TxtError: GoTo Name01
Sheets("MODELO - NFS").Copy Before:=Sheets("MODELO - DEMAIS"): ActiveSheet.Name = shtname
Application.ScreenUpdating = True
End Sub
Expected result:
And:
Sub COPIAR_MODELO()
Application.ScreenUpdating = False
Dim i As Integer, x As Integer
Dim shtname As String
Dim WSDummy As Worksheet
Dim TxtError As String
Dim counter As Long
TxtError = ""
shtname = Format(Now(), "dd mm yyyy")
On Error Resume Next
Set WSDummy = Sheets(shtname)
If Not (WSDummy Is Nothing) Then TxtError = "Name taken, additional sheet added!"
If TxtError <> "" Then MsgBox "" & TxtError: GoTo Name01
If TxtError = "" Then GoTo NameOK
Name01:
For counter = 1 To 100 Step 1
counter = counter + 1
shtname = Format(Now(), "dd mm yyyy") & " - " & counter
Next counter
NameOK:
Sheets("MODELO - NFS").Copy Before:=Sheets("MODELO - DEMAIS"): ActiveSheet.Name = shtname
Application.ScreenUpdating = True
End Sub
Expected result:
I will assign this code to a shape to create the sheets based on the current date.
I prefer result 2.
Copy Template
Sub CopyTemplate()
Const PROC_TITLE As String = "Copy Template"
Const TEMPLATE_WORKSHEET_NAME As String = "MODELO - NFS"
Const BEFORE_WORKSHEET_NAME As String = "MODELO - DEMAIS"
Const DATE_FORMAT As String = "dd mm yyyy"
Const DATE_NUMBER_DELIMITER As String = " - "
Const FIRST_NUMBER As Long = 2
Const FIRST_WORKSHEET_HAS_NUMBER As Boolean = False
Const INPUT_BOX_PROMPT As String = "Input number of worksheets to create."
Const INPUT_BOX_DEFAULT As String = "1"
Dim WorksheetsCount As String: WorksheetsCount _
= InputBox(INPUT_BOX_PROMPT, PROC_TITLE, INPUT_BOX_DEFAULT)
If Len(WorksheetsCount) = 0 Then Exit Sub
Dim DateName As String: DateName = Format(Date, DATE_FORMAT)
Dim NewName As String: NewName = DateName
Dim NewNumber As Long: NewNumber = FIRST_NUMBER
If FIRST_WORKSHEET_HAS_NUMBER Then
NewName = NewName & DATE_NUMBER_DELIMITER & NewNumber
NewNumber = NewNumber + 1
End If
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim wsTemplate As Worksheet
Set wsTemplate = wb.Worksheets(TEMPLATE_WORKSHEET_NAME)
Dim wsBefore As Worksheet
Set wsBefore = wb.Worksheets(BEFORE_WORKSHEET_NAME)
Dim wsNew As Worksheet
Dim WorksheetNumber As Long
Application.ScreenUpdating = False
Do While WorksheetNumber < WorksheetsCount
On Error Resume Next
Set wsNew = wb.Worksheets(NewName)
On Error GoTo 0
If wsNew Is Nothing Then
wsTemplate.Copy Before:=wsBefore
wsBefore.Previous.Name = NewName
WorksheetNumber = WorksheetNumber + 1
Else
NewName = DateName & DATE_NUMBER_DELIMITER & NewNumber
NewNumber = NewNumber + 1
Set wsNew = Nothing
End If
Loop
Application.ScreenUpdating = True
MsgBox WorksheetsCount & " worksheet" & IIf(WorksheetsCount = 1, "", "s") _
& " created.", vbInformation, PROC_TITLE
End Sub
If you overplay it...
Sub DeleteCreatedWorksheets()
Const PROC_TITLE As String = "Delete Created Worksheets"
Const BEFORE_WORKSHEET_NAME As String = "MODELO - DEMAIS"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim wsBefore As Worksheet
Set wsBefore = wb.Worksheets(BEFORE_WORKSHEET_NAME)
Dim wsIndex As Long: wsIndex = wsBefore.Index - 1
If wsIndex > 0 Then
Application.DisplayAlerts = False
Dim n As Long
For n = wsIndex To 1 Step -1
wb.Worksheets(n).Delete
Next n
Application.DisplayAlerts = True
End If
MsgBox wsIndex & " created worksheet" _
& IIf(wsIndex = 1, "", "s") & " deleted.", _
vbInformation, PROC_TITLE
End Sub

I have multiple xlsx file(which are not opened). I want to copy selected range value of each Workbook to the single row

I have multiple workbooks each having the same sheet. I want to Copy the sheet's value to the master book.
I want to copy the selected range value of each Workbook to the single row of the new workbook.
Also, how can I retrieve the options button caption from the source workbook? Where Option buttons are ActiveX and linked cells.
If the options button is checked, copy the options button caption value to the destination cell.
Also I wish to add yyyy , mm,dd values in Date format (yyyy/mm/dd)
Sub test1()
Dim Wsh As New IWshRuntimeLibrary.WshShell
Dim result As WshExec
Dim fileData() As String
Dim path As String
Dim cmd As String
path = ThisWorkbook.path & "\Book1"
cmd = "dir" & path & "/Test"
Set result = Wsh.Exec("%ComSpec% /c" & cmd)
Do While result.Status = 0
DoEvents
Loop
fileData = Split(result.StdOut.ReadAll, vbCrLf)
Dim i As Long
i = 4
For Each strData In fileData
Cells(i, 2).Value = strData
If Cells(i, 2).Value <> "" Then
Cells(i, 3).Value = "='" & path & "\[" & strData & "]sheet1'!F1" '
Cells(i, 4).Value = "='" & path & "\[" & strData & "]sheet1'!C4" '
End If
i = i + 1
Next
End Sub
Retrieve Data From Closed Workbooks 2
Sub RetrieveDataFromClosedWorkbooks2()
Const SOURCE_SUBFOLDER_NAME As String = "Book1"
Const SOURCE_FILE_PATTERN As String = "*.xlsx"
Const SOURCE_WORKSHEET_NAME As String = "Sheet1"
Const SOURCE_CELL_ADDRESSES_LIST As String = "F1,C4"
Const DESTINATION_WORKSHEET_NAME As String = "Sheet1"
Const DESTINATION_FIRST_CELL_ADDRESS As String = "B4"
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim dws As Worksheet: Set dws = dwb.Worksheets(DESTINATION_WORKSHEET_NAME)
Dim dCell As Range: Set dCell = dws.Range(DESTINATION_FIRST_CELL_ADDRESS)
Dim pSep As String: pSep = Application.PathSeparator
Dim sFolderPath As String
sFolderPath = dwb.Path & pSep & SOURCE_SUBFOLDER_NAME
If Right(sFolderPath, 1) <> pSep Then sFolderPath = sFolderPath & pSep
Dim sFileNames() As String
sFileNames = FileNamesToArray(sFolderPath, SOURCE_FILE_PATTERN)
If UBound(sFileNames) = -1 Then
MsgBox "No files found.", vbExclamation
Exit Sub
End If
Dim sAddresses() As String
sAddresses = Split(SOURCE_CELL_ADDRESSES_LIST, ",")
Dim sf As Long
Dim sa As Long
Dim dFormula As String
For sf = 0 To UBound(sFileNames)
dCell.Offset(sf).Value = sFileNames(sf) ' source file name
For sa = 0 To UBound(sAddresses)
dFormula = "='" & sFolderPath & "[" & sFileNames(sf) _
& "]" & SOURCE_WORKSHEET_NAME & "'!" & sAddresses(sa)
'Debug.Print dFormula
With dCell.Offset(sf, sa + 1)
'Debug.Print .Address, sf, sFileNames(sf), sa, sAddresses(sa)
.Formula = dFormula
'.Value = .Value ' to keep only values
End With
Next sa
Next sf
MsgBox "Data retrieved.", vbInformation
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Returns the names of all files of a folder in an array.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function FileNamesToArray( _
ByVal FolderPath As String, _
Optional ByVal FilePattern As String = "*.*") _
As String()
Const DirSwitches As String = "/b/a-d"
Dim pSep As String: pSep = Application.PathSeparator
If Right(FolderPath, 1) <> pSep Then FolderPath = FolderPath & pSep
Dim ExecString As String ' '%comspec%' or 'cmd.exe' ?
ExecString = "%comspec% /c Dir """ _
& FolderPath & FilePattern & """ " & DirSwitches
Dim pString As String
pString = CreateObject("WScript.Shell").Exec(ExecString).StdOut.ReadAll
If Len(pString) = 0 Then ' multiple issues: no file, invalid input(s)
FileNamesToArray = Split("") ' ensure string array: 'LB = 0, UB = -1'
Else
pString = Left(pString, Len(pString) - 2) ' remove trailing 'vbCrLf'
FileNamesToArray = Split(pString, vbCrLf)
End If
End Function

How to save in Sharepoint export .txt file from table using VBA

I want export table from Worksheet to .txt file. I need save txt file in the same location on Sharepoint like .xlsm
If I used filePath = "C:\Excel\test.txt" it works, but if I want use htpp://sharepointsite... i received error.
Sub ExportToTxt()
Dim fileStream As Object
Set fileStream = CreateObject("ADODB.Stream")
Dim filePath As String
Dim myFileName As String
Dim cellVal As Variant
Dim row As Integer
Dim col As Integer
Dim rangeToExport As Range
Dim exportData, myTab As String
' filePath = "C:\Excel\test.txt"
filePath = "https://mycompany.sharepoint.com/sites/MySite/TestLibrary/" & fileNameFromXlsm & "newFormat.txt"
fileStream.Open
fileStream.Charset = "UTF-8"
Set rangeToExport = Range("Table1[#All]")
For row = 1 To rangeToExport.Rows.Count
exportData = ""
For col = 1 To rangeToExport.Columns.Count
If col = 1 Then myTab = "" Else myTab = vbTab
cellVal = rangeToExport.Cells(row, col).Value
exportData = exportData & myTab & cellVal
Next col
fileStream.WriteText exportData & vbCrLf ' vbCrLf: linebreak
Next row
fileStream.SaveToFile filePath, 2 ' 2: Create Or Update
fileStream.Close
End Sub

Double loop - cycling through subfolders and files for consolidation

I am a bit stuck with finishing the script below.
I got to this point and it does the basic thing I need it to do but it does need a bit of tweaking to get perfect.
It does the following: 1-pickup and prep master output file; 2- open each file in folder 'xls' and copy data from the designated sheet at the end of the master output file; 3-final edit of the master file; 4-save master file with name based on the input archives.
Where I need help is and was unable to fix up is: I want the script to cycle through subfolders in 'xls' folder and create a single master for each subfolder in 'xls' collecting data from files in that subfolder and name it after subfolder.
I understand I need another loop for subfolders but I am not really good with dirs in vba. Would this require a major overhaul?
Sub Joiner()
'Application.EnableCancelKey = xlDisabled
Dim folderPath As String
Dim FileNAME As String
Dim wb As Workbook
Dim Masterwb As Workbook
Dim sh As Worksheet
Dim NewSht As Worksheet
Dim FindRng As Range
Dim PasteRow As Long
Dim DayVar As String
Dim RangeVar As Variant
Dim LastRow As Long
Dim Targetsh As Worksheet
Dim RecordsCount As Long
' set master workbook
Workbooks.Open FileNAME:="C:\TA\output\Master Template.xlsx"
Set Masterwb = Workbooks("Master Template.xlsx")
Set Targetsh = Masterwb.Sheets("Data")
With ActiveWorkbook.Sheets("Data")
.Range("A1").FormulaR1C1 = "SysTime"
.Range("B1").FormulaR1C1 = "Seq#"
.Range("C1").FormulaR1C1 = "A1"
.Range("D1").FormulaR1C1 = "F2"
.Range("E1").FormulaR1C1 = "F3"
.Range("F1").FormulaR1C1 = "T4"
.Range("G1").FormulaR1C1 = "T5"
.Range("H1").FormulaR1C1 = "T6"
.Range("I1").FormulaR1C1 = "T7"
.Range("J1").FormulaR1C1 = "T8"
.Range("K1").FormulaR1C1 = "A9"
.Range("A1:K1").Font.Bold = True
.Range("A1:K1").Interior.ColorIndex = 19
.Range("L1").FormulaR1C1 = "Date"
.Range("M1").FormulaR1C1 = "Date/Seq#"
End With
folderPath = "C:\TA\xls\" 'contains folder path
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
Application.ScreenUpdating = False
FileNAME = Dir(folderPath & "*.xls*")
Do While FileNAME <> ""
Set wb = Workbooks.Open(folderPath & FileNAME)
'DayVar = Left(Right(wb.Name, 13), 8)
LastRow = wb.Sheets("Cleaned").Range("A1").End(xlDown).Row
RangeVar = wb.Sheets("Cleaned").Range("A2:K" & LastRow)
Targetsh.Range("A" & Rows.Count).End(xlUp)(2).Resize(UBound(RangeVar, 1), UBound(RangeVar, 2)) = RangeVar
wb.Close False
Exit_Loop:
Set wb = Nothing
FileNAME = Dir
Loop
Application.ScreenUpdating = True
With Masterwb.Sheets("Data")
.Range(Range("A2"), Range("A2").End(xlDown)).NumberFormat = "dd/mm/yyyy hh:mm:ss"
End With
LastRow = ActiveWorkbook.Sheets("Data").Range("A1").End(xlDown).Row
With ActiveWorkbook.Sheets("Data")
.Range("L2").FormulaR1C1 = "=INT(C1)"
.Range("M2").FormulaR1C1 = "=C12&""-""&C2"
End With
Range("L2").AutoFill Destination:=Range("L2" & ":L" & LastRow)
With ActiveSheet
.Columns("L:L").Cells = .Columns("L:L").Cells.Value
End With
Range("M2").AutoFill Destination:=Range("M2" & ":M" & LastRow)
With ActiveSheet
.Columns("M:M").Cells = .Columns("M:M").Cells.Value
End With
With Masterwb.Sheets("Data")
.Range(Range("L2"), Range("L2").End(xlDown)).NumberFormat = "dd/mm/yyyy"
End With
'Name the master output based on id
Dim FirstName As String
Dim InterName As String
Dim FinalName As String
Dim FilePath As String
FirstName = Dir("C:TA\Input\*.cab", vbNormal)
InterName = "Master Template " & Right(Left(FirstName, 12), 4)
'MsgBox FirstName
'MsgBox InterName
FilePath = "C:\TA\output"
ActiveWorkbook.SaveAs FileNAME:=FilePath & "\" & InterName & ".xlsx", _
FileFormat:=51, CreateBackup:=False
'
End Sub
Thank you for any advice.
With this code you can list excel files in a folder and subfolders
Sub ListSubfoldersFile() ' only one level subfolders
arow = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
mFolder = "F:\Download\" ' path to change
Set mainFolder = objFSO.GetFolder(mFolder)
StrFile = Dir(mFolder & "*.xls*")
Do While Len(StrFile) > 0
Cells(arow, 1).Value = mFolder & StrFile
arow = arow + 1
StrFile = Dir
Loop
For Each mySubFolder In mainFolder.subfolders
StrFile = Dir(mySubFolder & "\*.xls*")
Do While Len(StrFile) > 0
Cells(arow, 1).Value = mySubFolder & "\" & StrFile
arow = arow + 1
StrFile = Dir
Loop
Next
End Sub
Thank you Patel!
I used your solution to complement my current vba snippet.
It may be a bit clunky but it does what I need it to do.
Thank you.
Posting a solution below for the benefit of the community.
Sub MassJoiner()
'this is a version of joiner with subfolders
'Application.EnableCancelKey = xlDisabled
Dim folderPath As String
Dim FileNAME As String
Dim wb As Workbook
Dim Masterwb As Workbook
Dim sh As Worksheet
Dim NewSht As Worksheet
Dim FindRng As Range
Dim PasteRow As Long
Dim DayVar As String
Dim RangeVar As Variant
Dim LastRow As Long
Dim Targetsh As Worksheet
Dim RecordsCount As Long
Dim StrFile As String
Dim mFolder As String
Dim BatchCount As Long
Dim ID As String
Set objFSO = CreateObject("Scripting.FileSystemObject")
mFolder = "D:\TA\TEST\" ' path to change
Set mainFolder = objFSO.GetFolder(mFolder)
StrFile = Dir(mFolder & "*.xls*")
BatchCount = 0
Workbooks.Open FileNAME:="C:\TA\output\Master Template.xlsx"
For Each mySubFolder In mainFolder.subfolders
StrFile = Dir(mySubFolder & "\*.xls*")
Do While Len(StrFile) > 0
Set Masterwb = Workbooks("Master Template.xlsx")
Set Targetsh = Masterwb.Sheets("Data")
With ActiveWorkbook.Sheets("Data")
.Range("A1").FormulaR1C1 = "SysTime"
.Range("B1").FormulaR1C1 = "Seq#"
.Range("C1").FormulaR1C1 = "A1"
.Range("D1").FormulaR1C1 = "F2"
.Range("E1").FormulaR1C1 = "F3"
.Range("F1").FormulaR1C1 = "T4"
.Range("G1").FormulaR1C1 = "T5"
.Range("H1").FormulaR1C1 = "T6"
.Range("I1").FormulaR1C1 = "T7"
.Range("J1").FormulaR1C1 = "T8"
.Range("K1").FormulaR1C1 = "A9"
.Range("A1:K1").Font.Bold = True
.Range("A1:K1").Interior.ColorIndex = 19
.Range("L1").FormulaR1C1 = "Date"
.Range("M1").FormulaR1C1 = "Date/Seq# pair"
End With
'FileNAME = Dir(folderPath & "*.xls*")
'Do While FileNAME <> ""
Set wb = Workbooks.Open(mySubFolder & "\" & StrFile)
'DayVar = Left(Right(wb.Name, 13), 8)
LastRow = wb.Sheets("Cleaned").Range("A1").End(xlDown).Row
RangeVar = wb.Sheets("Cleaned").Range("A2:K" & LastRow)
Targetsh.Range("A" & Rows.Count).End(xlUp)(2).Resize(UBound(RangeVar, 1), UBound(RangeVar, 2)) = RangeVar
wb.Close False
'Exit_Loop:
' Set wb = Nothing
' FileNAME = Dir
'Loop
StrFile = Dir
Loop
With Masterwb.Sheets("Data")
.Range(Range("A2"), Range("A2").End(xlDown)).NumberFormat = "dd/mm/yyyy hh:mm:ss"
End With
LastRow = ActiveWorkbook.Sheets("Data").Range("A1").End(xlDown).Row
With ActiveWorkbook.Sheets("Data")
.Range("M2").FormulaR1C1 = "Date/Seq# pair"
.Range("m2").FormulaR1C1 = "=C12&""-""&C2"
End With
Range("L2").AutoFill Destination:=Range("L2" & ":L" & LastRow)
With ActiveSheet
.Columns("L:L").Cells = .Columns("L:L").Cells.Value
End With
Range("M2").AutoFill Destination:=Range("M2" & ":M" & LastRow)
With ActiveSheet
.Columns("M:M").Cells = .Columns("M:M").Cells.Value
End With
With Masterwb.Sheets("Data")
.Range(Range("l2"), Range("l2").End(xlDown)).NumberFormat = "dd/mm/yyyy"
End With
'Name the master output based on job id
Dim FirstName As String
Dim InterName As String
Dim FinalName As String
Dim FilePath As String
FirstName = mySubFolder
InterName = "Master Template " & Right(FirstName, 4)
ID = Right(FirstName, 4)
'MsgBox FirstName
'MsgBox InterName
FilePath = "C:\TA\output"
ActiveWorkbook.SaveAs FileNAME:=FilePath & "\" & InterName & ".xlsx", _
FileFormat:=51, CreateBackup:=False
ActiveWorkbook.Close False
BatchCount = BatchCount + 1
Application.Speech.Speak "Batch job" & BatchCount & "finalized. ID" & ID
Workbooks.Open FileNAME:="C:\output\Master Template.xlsx"
Next
Application.ScreenUpdating = True
End Sub

Search list of strings in txt file via excel

I have many txt files in my folder. I have also have a list of their names in column 1, i need to search separate 1 string in each files which are listed in column 2. If such txt is found then it should say "Found" or else not found.
i was trying to modify below code based on my requirement but i unable to do it as its giving me the error for which i don't know the solution.
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
Try this modification
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

Resources