mercredi 5 février 2020

loop through each row in a given range with if statement with multiple conditions in vba

I'm trying to loop trough each row in the range J16:P19, and with every iteration, it must be checked if the value in the cell = 3, and if the text in the corresponding coloumn (range J15:J19) is present in the range ( W1:W7).

eg. If the cell (K17) in the row (J17:P17) = 3 & the corresponding coloumn name (K15) of that cell is present in the range ( W1:W7); the value of in Q17 must be substracked by 1.

This should be done for every row in the range. My code looks like this:

private Sub CommandButton2_Click()

dim rng As Range
dim i As Range
dim row As Range
Set rng = Range("j16:p19")

For Each row In rng.Rows
    For Each i In row.Cells
       If i.Value = 3 & Cells(i,15) %in% Range("w1:w7") Then
           Cells(row,22).Value = Cells(row,17).Value -1
       Else
           Cells(row,22).Value = Cells(row,17).Value
       End if
    Next i
Next row 
End sub

It works when I select the range to be one column only, and without the second part of the if statement. Do you have any suggestions on have to solve my problem? thank you in advance

Aucun commentaire:

Enregistrer un commentaire