I'm trying to create a loop based on data in Column L. Data in Column L is formatted as Text and contains dates. If a match is found, the entire Row has to be highlighted in yellow.
Sub Forn()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
Dim strSearchText As String
strSearchText = Format(DateAdd("m", 2, Now()), "yyyymm")
Dim rngSearchArea As Range
Set rngSearchArea = ws.Range(Range("L10"), ws.Range("L" & ws.Range("L:L").Cells.Count).End(xlUp))
Dim strFirstFound As String
Dim rngCurrentFound As Range
Set rngCurrentFound = ws.Range("L10")
Set rngCurrentFound = rngSearchArea.Find(What:=strSearchText, After:=rngCurrentFound, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)
If rngCurrentFound Is Nothing Then
MsgBox "INGEN TREFF"
Exit Sub
End If
rngCurrentFound.Resize(1, 16).Offset(0, -11).Interior.ColorIndex = 6
strFirstFound = rngCurrentFound.Address
Dim rngSource As Range
Dim rngNextFound As Range
Do
Set rngNextFound = rngSearchArea.FindNext(rngCurrentFound)
If rngNextFound.Row > rngCurrentFound.Row Then
rngCurrentFound.Resize(1, 16).Offset(0, -11).Interior.ColorIndex = 6
Else
Set rngSource = ws.Range(rngCurrentFound, ws.UsedRange.Cells(ws.UsedRange.Cells.Count))
End If
Set rngCurrentFound = rngSearchArea.FindNext(rngCurrentFound)
Loop While rngCurrentFound.Address <> strFirstFound
End Sub
I'm getting Run-time error '1004': Method 'Range' of object '_Worksheet' failed.
This exact same code worked for me yesterday and I'm at a complete loss as to what needs to be changed here.
UPD: the error is caused by launching the Macro from PERSONAL.XLSB --
Set ws = ThisWorkbook.Worksheets(1)
no longer works as needed.
Worksheets(1)rather than a named sheet.ThisWorkbookis the Workbook where the code lives. If you move code toPersonal, it will access the first sheet ofPersonal- which probably don't exists.ws. It should be this:Set rngSearchArea = ws.Range(ws.Range("L10"), ws.Range("L" & ws.Range("L:L").Cells.Count).End(xlUp)). You forgot to qualify the worksheet forRange("L10")