Home > Enterprise >  For Loop with If-Or Statement VBA
For Loop with If-Or Statement VBA

Time:01-09

I have hard-coded for ever two cells in an excel column to count if either the first or second have a value of 1. It worked this way (but also written out for every cell applicable so is inefficent):

If Range("D10").Value = 1 Or Range("D11").Value = 1 Then
    x = x   1
Else
    x = x   0
End If

I am trying to refactor it. My thought was to do a for loop, with an if and an or statement (similar to in my current code), but receive a syntax error. My attempt:

Sub refactor()
Dim x As Integer
x = 0
For Each c In Range("D2-D13").Cells
    If c.Value =1 OR (c 1).Value = 1 Then
    x = x   1
    Else
    x = x   0

    End If
Range("A19") = x
End Sub

All I can find is for loops with if statements in them, but never the added "or" condition considered. VBA is new to me. Is there a way I can code this?

CodePudding user response:

Let alone the sense of the code if you really want to count like in the code you posted and I put here as well

If Range("D10").Value = 1 Or Range("D11").Value = 1 Then
    x = x   1
Else
    x = x   0
End If

then you could use this code

Sub countCode()

    Dim x As Long
    Dim sngCell As Range
    Dim rg As Range

    Set rg = Range("D2:D13")
    For Each sngCell In rg
        If sngCell.Value = 1 Or sngCell.Offset(1).Value = 1 Then
            x = x   1
        End If
    Next sngCell
    
    Debug.Print x
    
End Sub

CodePudding user response:

for loop in enough to run entire range itn't required "or c.offset(1,0).value = 1" because "or" operator used to any one condition is true it will allow to run the code.

"if c.Value = 1 and c.Offset(1, 0).Value = 1 Then" = this case is used for if both the statement is true then only if condition allow to run the code. are u looking for this?

Sub refactor()
Dim x As Integer
Dim c As Range

x = 0

For Each c In Range("D2:D13")
   'if c.Value = 1 Or c.Offset(1, 0).Value = 1 Then'this line is same as below line
    if c.value = 1 then
        x = x   1
    End If
Next c

Range("A19") = x
End Sub
  •  Tags:  
  • Related