I have a table which changes daily. At times the text "AB12" is found in column A in multiples of three. When this happens I need VBA to recognize it has occurred, find the row it has occurred on and then average the values in columns C,E,G,I,K,M,O,and Q on that row. This average then needs to be compared to the average for the next row and the row after that deleting all but the row with the highest average.
The code I have written thus far is found below.
Sub FindAB12()
Columns("A:Q").Select
Set rngRange = Selection.CurrentRegion
lngNumRows = rngRange.Rows.Count
lngFirstRow = rngRange.Row
lngLastRow = lngFirstRow + lngNumRows - 1
lngCompareColumn = ActiveCell.Column
For lngCurrentRow = lngLastRow To lngFirstRow Step -1
If (Cells(lngCurrentRow, lngCompareColumn).Text = "AB12" And Cells(lngCurrentRow + 1, lngCompareColumn).Text = "AB12") Then _
AB121 = Application.WorksheetFunction.Average(Sheet1.Range("C" & lngCurrentRow & ":Q" & lngCurrentRow))
AB122 = Application.WorksheetFunction.Average(Sheet1.Range("C" & (lngCurrentRow + 1) & ":Q" & (lngCurrentRow + 1)))
AB123 = Application.WorksheetFunction.Average(Sheet1.Range("C" & (lngCurrentRow + 2) & ":Q" & (lngCurrentRow + 2)))
Next lngCurrentRow
If AB1211 > AB122 And AB1211 > AB123 Then
Rows(lngCurrentRow + 1 And lngCurrentRow + 2).Delete
ElseIf AB122 > AB123 And AB122 > AB121 Then
Rows(lngCurrentRow And lngCurrentRow + 2).Delete
ElseIf AB123 > AB122 And AB123 > AB121 Then
Rows(lngCurrentRow And lngCurrentRow + 1).Delete
End If
End Sub
In a separate module I am having the sub called upon opening the tab. It would be expected that upon opening this tab only a single row called AB12 would exist in sequential rows (though another AB12 could exist in a later row). The code works up until I try to average (I have used the same code to successfully find and delete these duplicated rows when calculation was not needed). When it plays and hits the second average function I get the error "Run-time error '1004': Method 'Range' of object '_Worksheet' failed
. I am fairly new to VBA and after looking at a lot of code that others have created I have not been able to solve the problem. I hope someone out there can help. I have never used this forum before and am not sure how to best upload my current code, hope my problem and current code is clear.