excelvba

I need my FOR IF statement to check a range of cells for values


I have a FOR IF statement that I want to check a range of cells (5 cells per row) for any value. if any cell within that range has a value then another cell on the same row will have its value changed. But I know i'm not going about this the right way. Can anyone help?

    'place rate type into callforward
 Dim r As Integer
     For r = 17 To 600
   If Cells("r", 14).Value <> "" Or Cells("r", 15).Value <> "" Or Cells("r", 16).Value <> "" Or Cells("r", 17).Value <> "" Or Cells("r", 18).Value <> "" Then
  Cells(r, 9).Value = "WKD"
   End If
   Next r

Solution

  • For the shown task, you can do this without a loop at all by defining a range to have a formula and then converting the formula to its values. I also recommend using COUNTBLANK because both COUNTIF(S) and COUNTA will identify a cell that contains ="" as not blank (for example, if the cell contains a formula and the result is ""). I would consider that a blank cell and a cell you would not want to be counted as not blank per your posted code.

    That all being said, something like this should work for you:

    Sub tgr()
        
        Dim ws As Worksheet:    Set ws = ActiveWorkbook.ActiveSheet
        
        With ws.Range("I17:I600")
            .Formula = "=IF(COUNTBLANK(N" & .Row & ":R" & .Row & ")<5,""WKD"","""")"
            .Value = .Value
        End With
        
    End Sub