View Full Version : multiple ranges to if statement
Hi, how can I apply multiple ranges to this statement?
I want to apply this to ranges aj12,aj16,aj20 etc....
 
 
If there is a way to do this each time a set of 3 come up (eg 3,9,12,15...) that would be even better..
 
If Range("AJ8") = 3 Then
MsgBox "HI"
End If
 
Is there a way to do this without making 24 if statements.
Bob Phillips
04-24-2011, 10:59 AM
If Range("AJ8").Value2 = 3 Or Range("AJ12").Value2 = 3 OR Range("AJ16").Value2 = 3 Or Range("AJ20").Value2 = 3 Then 
    MsgBox "HI" 
End If
is there a way that if the range is divisible by 3 as a whole number then...
Kenneth Hobs
04-24-2011, 11:16 AM
If your numbers are incremented by a specific number like 4 in your first example:
Sub t()
  Dim i As Long
  For i = 12 To 20 Step 4
    If Range("AJ" & i).Value2 = 3 Then
      MsgBox "AJ" & i & " = 3"
      Exit For
    End If
  Next i
End Sub
If there is no logic to your incremental numbers then:
Sub t2()
  Dim a() As Variant, element As Variant
  a() = Array("AJ3", "AJ9", "AJ12", "AJ15")
  For Each element In a()
    If Range(element).Value2 = 3 Then
      MsgBox element & " = 3"
      Exit For
    End If
  Next element
End Sub
I used Kennith's code and it works well. Is there a way to adapt = 3 to = a number divisible by 3? 
 
eg; = 3,6,9,12,15,18 etc...
 
Thanks so much guys.
mbarron
04-24-2011, 01:24 PM
change  If Range(element).Value2 = 3 Then  to 
 If Range(element).Value2 Mod 3 = 0 Then
Kenneth Hobs
04-24-2011, 02:49 PM
You will probably not want it to return empty cells either so add to IF:
Sub t()
    Dim i As Long, cell As Range
    For i = 12 To 20 Step 4
        Set cell = Range("AJ" & i)
        If cell.Value2 Mod 3 = 0 And cell.Value2 <> Empty Then
            MsgBox "AJ" & i & " = Multiply of 3"
            Exit For
        End If
    Next i
End Sub
mikerickson
04-24-2011, 03:46 PM
This doesn't loop
On Error Resume Next
    If Application.Product(Range("Aj8,aj12,aj16").SpecialCells(xlCellTypeConstants, xlNumbers)) Mod 3 <> 0 Then
        On Error GoTo 0
        MsgBox "none are divisible by 3"
    Else
        On Error GoTo 0
        MsgBox "at least one is divisible by 3"
    End If
Note: This works only because 3 is prime.
Powered by vBulletin® Version 4.2.5 Copyright © 2025 vBulletin Solutions Inc. All rights reserved.