VBA & Macro Problems

Search Multiple Text Files for a String with Excel VBA

Chanuka GeekiyanageChanuka Geekiyanage Nov 25, 2026 869 views

Question details

Search all text files in a selected folder for a string and report each matching file name, line number, folder path, and line of text.

Search Multiple Text Files for a String with Excel VBA
Product
Microsoft Office VBA
Device & OS
not provided
Scenario
The user wants a macro that searches multiple .txt files and can count occurrences of the search string.
Observed behavior
The desired result is a list of matching lines with their source details and occurrence counts.
Before you start

Use desktop Excel on Windows and save the workbook as an Excel Macro-Enabled Workbook (.xlsm). Identify the folder and search text; the macro searches files in that folder only, not its subfolders.

Solution 1Recommended

Search a folder of text files with an Excel VBA macro

Use this macro to write one row per matching line, including the number of non-overlapping matches on that line.

The macro uses the Windows FileSystemObject through late binding, so you do not need to add a Microsoft Scripting Runtime reference. Matching is case-insensitive.

Files are read using the system's default text encoding. UTF-8 or other encodings may require a different reader, especially if text contains non-ASCII characters.

1
Open the VBA editor

In desktop Excel on Windows, open your .xlsm workbook and press Alt+F11. Select Insert > Module.

2
Paste the macro

Paste this code into the module: Sub SearchTextFiles() Dim fso As Object, folder As Object, file As Object, stream As Object Dim picker As Object, results As Worksheet Dim folderPath As String, searchText As String, lineText As String Dim lineNumber As Long, resultRow As Long Dim pos As Long, hits As Long, totalHits As Long searchText = InputBox("Enter the text to find:", "Search text files") If Len(searchText) = 0 Then Exit Sub Set picker = Application.FileDialog(msoFileDialogFolderPicker) picker.Title = "Select the folder containing text files" If picker.Show <> -1 Then Exit Sub folderPath = picker.SelectedItems(1) On Error GoTo SearchError Set fso = CreateObject("Scripting.FileSystemObject") Set folder = fso.GetFolder(folderPath) Set results = ThisWorkbook.Worksheets.Add results.Range("A1:E1").Value = Array("File name", "Line number", "Folder path", "Matching text", "Occurrences") results.Columns("A").NumberFormat = "@" results.Columns("C:D").NumberFormat = "@" resultRow = 2 For Each file In folder.Files If LCase$(fso.GetExtensionName(file.Name)) = "txt" Then Set stream = fso.OpenTextFile(file.Path, 1, False) lineNumber = 0 Do Until stream.AtEndOfStream lineText = stream.ReadLine lineNumber = lineNumber + 1 hits = 0 pos = 1 Do pos = InStr(pos, lineText, searchText, vbTextCompare) If pos = 0 Then Exit Do hits = hits + 1 pos = pos + Len(searchText) Loop If hits > 0 Then If resultRow > results.Rows.Count Then Err.Raise vbObjectError + 1, , "The results exceed the worksheet row limit." results.Cells(resultRow, 1).Value = file.Name results.Cells(resultRow, 2).Value = lineNumber results.Cells(resultRow, 3).Value = folderPath results.Cells(resultRow, 4).Value = lineText results.Cells(resultRow, 5).Value = hits resultRow = resultRow + 1 totalHits = totalHits + hits End If Loop stream.Close Set stream = Nothing End If Next file MsgBox "Matching lines: " & (resultRow - 2) & vbCrLf & "Total occurrences: " & totalHits, vbInformation Exit Sub SearchError: MsgBox "Search stopped: " & Err.Description, vbExclamation On Error Resume Next If Not stream Is Nothing Then stream.Close End Sub

3
Run the search

Return to Excel, press Alt+F8, select SearchTextFiles, and click Run. Enter the search string and select the folder when prompted.

4
Review the results

Open the newly added worksheet to see each matching line and its count. The completion message also shows the total number of occurrences.

Search a folder of text files with an Excel VBA macro
Text and macro limits: Enable macros only for workbooks you trust. Excel cells can hold up to 32,767 characters, so unusually long lines may not fit in full. If a file cannot be read, the macro stops and reports an error; results already written remain on the sheet.
Free Microsoft Office alternative

Review search results in WPS Office

WPS Office is a free, lightweight Office alternative with a familiar interface and support for common Microsoft Office formats, making it easy to move spreadsheets between applications. Use Excel for the Windows VBA search above; WPS Office is an option for reviewing the resulting spreadsheet, not a guaranteed replacement for running that macro.

Review matching file names, line numbers, paths, and text in a spreadsheetOpen and edit Microsoft Excel XLSX filesUse a familiar spreadsheet interface for an easier transitionWork with a free, lightweight Office alternative
microsoft office alternative - wps office

Frequently Asked Questions

Does the macro search subfolders?

No. The folder picker selects one folder, and the macro searches only the .txt files directly inside it.

How are occurrences counted?

The macro counts non-overlapping, case-insensitive matches on each line. The Occurrences column shows the count for that line, and the completion message shows the total.

Can I make the search case-sensitive?

In the VBA editor, change vbTextCompare to vbBinaryCompare in the InStr line, then run SearchTextFiles again.

Why does the macro stop on a text file?

A file may be inaccessible or use an encoding the default reader does not handle as expected. Check the reported error and file permissions; UTF-8 files may need a different text reader.

Can I run this macro in Excel for the web?

No. Open the .xlsm workbook in desktop Excel on Windows, where the VBA editor and Windows FileSystemObject are available.