Search code examples
vbaexcelexcel-2013

Fill Each Cell With Formula


I am attempting to write a macro that will
1) store the value of each cell in column A in a variable searchstring
the pieces of code that I Think does this is

lr = Cells(Rows.Count, 2).End(xlUp).Row
  For i = 2 To lr
      searchstring = ws.Cells(i, 1).Value

2) Take the variable searchstring and determine if it exists in column A of the sheet called rsca.
4) If it does update column N with Yes
5) If it does not update column N with No

This is my full syntax, but everytime I step through my code it hits the For line and immediately jumps to the End Function My worksheet has data in it, column A has roughly 40 rows to be precise (but this could fluctuate up or down, so I do not want to hardcode an end cell)

How should this syntax be altered so that it will achieve my desired result above?

Public Function CheckIfCurrent()
    Dim ws As Worksheet, searchstring As String, i As Long
    Set ws = Sheets("ers")

    lr = Cells(Rows.Count, 2).End(xlUp).Row
    For i = 2 To lr
      searchstring = ws.Cells(i, 1).Value
      With .Range("N2:N" & .Cells(.Rows.Count, "A").End(xlUp).Row)
         .Formula = IIf(IsError(Application.Match(searchstring, Sheets("rsca").Columns(1), 0)), "No", "Yes")
         .Value = .Value
      End With
    Next i        
End Function

Solution

  • How about this?

    Public Sub CheckIfCurrent()
        Dim searchstring As String
        Dim i As Long
    
        With ThisWorkbook.Worksheets("ers")
            lr = .Cells(.Rows.Count, 1).End(xlUp).Row
            For i = 2 To lr
                searchstring = .Cells(i, 1).Value
                With .Range("N2:N" & lr)
                    .Formula = IIf(IsError(Application.Match(searchstring, Sheets("rsca").Columns(1), 0)), "No", "Yes")
                    .Value = .Value
                End With
            Next i 
        End With 
    End Sub