0

I have a sheet in which Column "A" contains values. I want to collect the row numbers in a new sheet where string "Code: " is found. I want to write VBA code to achieve this. For example :

Sheet1 :

RowNo | Column A
------|---------
 1    | Hello World
 2    | Good morning
 3    | Code: 46904A65
 4    | Excuse
 5    | Code: 4523S45

Output Sheet :

RowNo | Column A
------|---------
 1    | 3
 2    | 5

Explanation : String "Code: " found in 3rd and 4th row of sheet 1. So output sheet contains those row numbers in it.

The following code is not working :

Set stTempData = Sheets("Output Sheet")
stTempData.Select

Set mainsheet = Sheets("Sheet1")
mainsheet.Select
k = Range("a65536").End(xlUp).Row

i = 1
Do While i < k

Set r = stTempData.Range("a65536").End(xlUp).Offset(1, 0)

If InStr(ActiveSheet.Cells(i, 0).Value, "Code:") > 0 Then
    r.Offset(i, 0).Value = ActiveCell.Row - 1
    j = i
    r.Offset(j + 1, 1).Value = ActiveCell.Row - 2
End If

i = i + 1
Loop
Sandeep Kushwah
  • 590
  • 1
  • 18
  • 35

1 Answers1

2

Put this in A1 in the output sheet:

=IFERROR(AGGREGATE(15,6,ROW(Sheet1!$A$1:$A$5)/(ISNUMBER(SEARCH("Code",Sheet1!$A$1:$A$5))),ROW(1:1)),"")

And copy down till you get blanks.


As to your code:

There is no column 0 So your Cells() needs to change to 1. Also you do not want to offset r. One more thing you had activesheet and activecell which was throwing it off.:

Set stTempData = Sheets("Output Sheet")
stTempData.Select

Set mainsheet = Sheets("Sheet1")
mainsheet.Select
k = Range("a65536").End(xlUp).Row

i = 1
Do While i <= k

    Set r = stTempData.Range("a65536").End(xlUp).Offset(1, 0)

    If InStr(mainsheet.Cells(i, 1).Value, "Code:") > 0 Then
        r.Value = mainsheet.Cells(i, 1).Row
    End If

    i = i + 1
Loop
Scott Craner
  • 148,073
  • 10
  • 49
  • 81