Geographos
Geographos

Reputation: 1486

VBA Excel if statement for odd & even values

I would like to set the IF statement for odd & even values in VBA Excel.

This is an idea, which I got after this query here:

VBA Excel run some parts of the code only once when using command buttons

My code is related to another part of the code above and looks as follows:

 Public Sub ResizeCiv2()
   ' image autoresize code
   Dim targetSheet As Worksheet
   Dim targetRange As Range
   Dim targetShape As Shape


  ' Define the sheet that has the pictures
   Set targetSheet = ThisWorkbook.ActiveSheet
   ' Define the range the images is going to fit
   Set targetRange = targetSheet.Range("C3:K24")


   ' Loop through each Shape in Sheet
    For Each targetShape In targetSheet.Shapes
    ' Check "picture" word in name
    If targetShape.Name Like "*Picture*" Then
        ' Call the resize function
        SizeToRange targetShape, targetRange
    End If

   Next targetShape

   'elements + numeration code

   Dim odd, even As Range
   Set even = ActiveSheet.Range("C51")
   Set odd = ActiveSheet.Range("C52")

   If even.Value = "TRUE" Then
   Call CivBox
   Call Divider
   ActiveSheet.Cells(51, 4).Value = ActiveSheet.Cells(51, 4).Value + 1
   End If
   If odd.Value = "FALSE" Then
   ActiveSheet.Cells(52, 4).Value = ActiveSheet.Cells(52, 4).Value + 1
   ActiveSheet.Range("M15").Value = Range("D52")
   End If

  End Sub

No error, but no reaction at all. I want to have this condition working. enter image description here

Basically I set the ISEVEN function for adjacent columns (C51 and C52), which in relation accordingly to D51 and D52 returns TRUE or FALSE. I would like to use this value in my IF statement. I don't understand why doesn't it work? Shall I write the VBA code for odd & even values?

Upvotes: 0

Views: 4791

Answers (2)

BJ2M
BJ2M

Reputation: 61

If I understand your problem correctly, the IF condition is not running because the condition you set is a String ("TRUE" and "FALSE"), while it's in fact a Boolean in Excel.

You should use the following:

If even.Value = True Then
...
End If

Boolean are recognized in VBA. So no need to use "TRUE" or "FALSE", but simply True or False.

Upvotes: 2

Chronocidal
Chronocidal

Reputation: 7951

This is False:

If Even.Value = "TRUE" Then
If Odd.Value = "FALSE" Then

This is True:

If Even.Value = True Then
If Odd.Value = False Then

And this is simpler:

If Even.Value Then
If Not Odd.Value Then

You are trying to compare a Boolean with a String

Upvotes: 2

Related Questions