I need to search through files within a directory for the occurrences of a string and return a count.
For testing I have put 4 workbooks with 5 worksheets each into C:\test directory. I am looking for a count of the occurrences of the word ammonia anywhere within the workbooks. The code I am using is retuning "0" even though I am certain it exists. I believe its because lookin does not work with merged cells. Are there any tricks for making this work?
Sub LoopThroughFiles()
Range("'sheet1'!A6:M10000").ClearContents
Dim directory As String, fileName As String, sheet As Worksheet, i As Integer, j As Integer
directory = "C:\Test\"
fileName = Dir(directory & "*.xl??")
i = 5
Do While fileName <> ""
i = i + 1
If fileName <> "" Then
Dim wbk As Workbook
With wbk
Set wbk = Workbooks.Open(directory & fileName)
End With
Dim sh As Worksheet
Dim found As Range
Dim count As Integer
For Each sh In wbk.Worksheets
Set found = sh.Cells.Find(what:="Ammonia", LookIn:=xlFormulas)
If Not found Is Nothing Then
sh.Activate
found.Select
count = count + sh.Range(found.Address).Offset(0, 3).Value
Else
End If
Next sh
wbk.Close
End If
fileName = Dir()
Loop
Range("'Sheet1'!C2").Value = count
End Sub
Code is not finding the value in a merged cell.
Welcome to SO.
The code you have provided is close to what it should be. However, it will only find one occurrence per worksheet. I am not sure if that's by design, so in the following code I'm demonstrating how you can find all the occurrences per worksheet.
Also, I am not sure I understand the logic of how you increase the
count
in each loop. Currently your code finds the cell whose value is "Ammonia" and then goes 3 cells to the right and adds whatever value is there tocount
. Again I am not sure if that's by design.Also, you don't need either of
sh.Activate
andfound.Select
.Below is the code I would suggest, along with comments that explain how it works.