简体   繁体   中英

VBA, For , For Each for entire range instead of each row

I am trying to put a value in each row, not the entire row. Currently now my data is putting "Failed" for the whole range when only one cell that OK applies to should be "Failed"

OK = primaryDoc.InsertPages(insertPoint, sourceDoc, startPage, endPage - startPage, False)

OK will return true or false.

Tried a For Loop

 For row_num = 8 To max_row
        If OK = True Then
            Range("O8:O43").value = "Completed"
        Else
            Range("O8:O43").value = "Failed"
        End If
        Next row_num

Tried a For each loop

Set a = Range("O3:O43")

For Each cell In a.Rows
    If OK = True Then
        a.value = "Completed"
    Else
        a.value = "Failed"
    End If
Next

Current results:

在此处输入图片说明

Expected :

在此处输入图片说明

Can anyone help me?

In your first code sample, you are always applying the value to all the cells. Don't do that. Only apply the value to the current cell, ie the one in the row of row_num . It will also depend on the current value of OK , of course. Your code does not seem to change the value of OK in each iteration of the loop, so it is not clear what it refers to.

 For row_num = 8 To max_row
        If OK = True Then
            Range("O" & row_num).value = "Completed"
        Else
            Range("O" & row_num).value = "Failed"
        End If
  Next row_num

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM