Search code examples
excelvbafindrangecopy-paste

finding row based off cell value and then copying paste based on the found row value - object variable not set


I'm still a big noobie at VBA so any advice would be so appreciated...

I am trying to copy a range from multiple worksheets with a specific name to one worksheet in the same workbook. The range is dynamic in that I know what column the range starts and ends on, but i don't know what row it will start and end on. I have the paste destination figured out, but I need help finding the row the range should start on. The range I want to copy should start after the row in which the cell value = "Open Items:" (i.e. if the row where the cell = "Open Items:" is 3, then i want my range to start at C4)

I'm having an issue with my .Find formula where it's returning nothing. I am confident that the range that I'm searching for "Open Items:" does have a cell that is equal to that. Please see below for my code:

Dim ws As Worksheet
Dim targetws As Worksheet
Dim FindRow As Range
Dim openitemrow As Long

Set targetws = Sheets("targetwsname")

'loop through each ws

For Each ws In ActiveWorkbook.Worksheets

'sets ws name constraint and then tries to find the starting row in the range
If ws.Name Like "*" & "Open" & "*" Then
     Set FindRow = ws.Range("C:C").Find("Open Items:", lookin:=xlValues, lookat:=xlWhole)
     openitemrow = FindRow.Row
'there needs to be values in c4 for me to copy data over but the data i need to copy is in a different location
          If Not IsEmpty(ws.Cells(4, "C")) Then
               ws.Range("C:F" & openitemrow).End(xlUp).Offset(1).Copy Destination:=targetws.Range("D" & Rows.Count).End(xlUp).Offset(1)

          End If
    End If
next ws 

Solution

  • If the entire cell value of the cell in question is "Open Items:" and the cell is always in the same column, then you can use match and this will already return it as a number

    openitemrow = Application.Match("Open Items:", ws.Range("C:C"), 0)