Search code examples
excelvbaformula

IF formula in VBA only returning True or False, not the criteria values


I am having trouble figuring out why my IF formula in VBA is not returning any of the criteria values. All I can get is the True or False value. This is what I currently have:
Cells(y, 11).Formula = "=IF((A" & y & ")+(B" & y & "))-((A" & y - 1 & ")+(B" & y - 1 & "))" > "($J$7*20),(((C" & y & ")-(C" & y - 1 & ")) * $J$7),(((A" & y & ")+(B" & y & "))-((A" & y - 1 & ")+(B" & y - 1 & ")))" Im sure its just a type-o or I am missing some quotations somewhere but if anyone can take a look at this and find what I am missing, that would be great. This is my whole code for better context.

Sub make_new_entry()

    Dim Layer_Increment, i As Integer
     Set Layer_Increment = Cells(7, 2)
     
    
    y = 10       'Set this to the first row number that gets a time entered.
    i = 0
    
    Do While i = 0
        If Cells(y, 1) = "" Then
            add_row y
            
            Cells(y, 1) = Format(Now(), "m/d/yy")
            Cells(y, 2) = Format(Now(), "h:mm")
            Cells(y, 3) = Cells(y - 1, 2) - ((Cells(y - 1, 2) - Layer_Increment * (y - 10)))
            Cells(y, 8).Formula = "=($H$7*(C" & y & "))+((0.5*'Data Reference'!F2)+(0.4*'Data Reference'!F3)+(0.3*'Data Reference'!F4)+(0.2*'Data Reference'!F5)+(0.1*'Data Reference'!F6)+(0.05*'Data Reference'!F7)+(0.01*'Data Reference'!F8)+(0.001*'Data Reference'!F9))+ $H$10+$N$7"
            Cells(y, 9).Formula = "=$I$10-(0.05*(C" & y & "-$C$10))"
            Cells(y, 10).Formula = "=(((A" & y & ")+(B" & y & "))-((A" & y - 1 & ")+(B" & y - 1 & ")))/((C" & y & ")-(C" & y - 1 & "))"
            Cells(y, 11).Formula = "=IF(A" & y & " + B" & y & ")-(A" & y - 1 & " + B" & y - 1 & ") > $J$7*20, (C" & y & " - C" & y - 1 & ") * $J$7, (A" & y & " + B" & y & ")-(A" & y - 1 & " + B" & y - 1 & ")"
            Cells(7, 6).Formula = "=((130-(H" & y & "))/$H$7)-('Build Information'!$F$6-(C" & y & "))"
            Cells(7, 4).Formula = "=Max(C:C)"
            Cells(7, 10).Formula = "=AverageIf(J11:J" & y & ",""<00:05:00"")"
            Cells(8, 11).Formula = "=Sum($K$10:(K" & y & ")"
            i = 1
       Else
            y = y + 1
        End If
    Loop
End Sub 

Solution

  • I suggest that you:

    1. fully qualify your ranges
    2. check your parenthesis and the order the calculations are made in Excel
    3. use variable names that are easy to understand (for example, instead of y use counter) .

    Regarding your formula, here is the way I'd fix it

    Cells(y, 11).Formula = "=IF((A" & y & "+B" & y & ")-(A" & y - 1 & "+B" & y - 1 & ") > $J$7*20,((C" & y & "-C" & y - 1 & ") * $J$7),((A" & y & "+B" & y & ")-(A" & y - 1 & "+B" & y - 1 & ")))"
    

    PS To fully qualify a range use this syntax

    Thisworkbook.Worksheets("Sheet1").Cells(y,11).Formula =