Home » excel » excel – Finding a string in multiple workbooks then finding the value of the cell next to it

excel – Finding a string in multiple workbooks then finding the value of the cell next to it

Posted by: admin May 14, 2020 Leave a comment


I found a code online to search through multiple workbooks and find a certain string, then print its address, workbook, worksheet and value. However, I need the code to print me the address, workbook, worksheet and the value of the cell next to it.

Sub SearchFolders()
Dim fso As Object
Dim fld As Object
Dim strSearch As String
Dim strPath As String
Dim strFile As String
Dim wOut As Worksheet
Dim wbk As Workbook
Dim wks As Worksheet
Dim lRow As Long
Dim rFound As Range
Dim strFirstAddress As String

On Error GoTo ErrHandler
Application.ScreenUpdating = False

'Change as desired
strPath = "C:\DondeSoftware\Vo Temp\Mock Portfolios\Feng Zheyuan\Portfolio Snapshots"
strSearch = "Cash:"

Set wOut = Worksheets.Add
lRow = 1
With wOut
    .Cells(lRow, 1) = "Workbook"
    .Cells(lRow, 2) = "Worksheet"
    .Cells(lRow, 3) = "Cell"
    .Cells(lRow, 4) = "Text in Cell"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fld = fso.GetFolder(strPath)

    strFile = Dir(strPath & "\*.xls*")
    Do While strFile <> ""
        Set wbk = Workbooks.Open _
          (Filename:=strPath & "\" & strFile, _
          UpdateLinks:=0, _
          ReadOnly:=True, _

        For Each wks In wbk.Worksheets
            Set rFound = wks.UsedRange.Find(strSearch)
            If Not rFound Is Nothing Then
                strFirstAddress = rFound.Address
            End If
                If rFound Is Nothing Then
                    Exit Do
                    lRow = lRow + 1
                    .Cells(lRow, 1) = wbk.Name
                    .Cells(lRow, 2) = wks.Name
                    .Cells(lRow, 3) = rFound.Address
                    .Cells(lRow, 4) = rFound.Value
                End If
                Set rFound = wks.Cells.FindNext(After:=rFound)
            Loop While strFirstAddress <> rFound.Address

        wbk.Close (False)
        strFile = Dir
End With
MsgBox "Done"

    Set wOut = Nothing
    Set wks = Nothing
    Set wbk = Nothing
 Set fld = Nothing
 Set fso = Nothing
 Application.ScreenUpdating = True
 Exit Sub

 MsgBox Err.Description, vbExclamation
 Resume ExitHandler
End Sub

I figured I could just add a variable like do something like

Dim cashcell as Range
cashcell = Range(rFound.Row, rFound.Column + 1)

But I was wrong. Anyone help alter this code?

How to&Answers:

To find the value of that cell use .Offset For example one column to the right, it would be rFound.Offset(,1).Value And if you want the address then rFound.Offset(,1).Address

If you want to return a range object then try this

Dim cashcell as Range
Set cashcell = rFound.Offset(,1)

You may also want to see Range.Offset property (Excel)


So I used rFound.Offset(0,1).Value and it worked. Thanks for all the help everyone!