Home » excel » excel – did I accidentally create a vba race condition?

excel – did I accidentally create a vba race condition?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I was hoping for some insight on a bug that I haven’t been able to replicate.

I have a very complicated worksheet that changes many variables to get a certain cell aa5 to return a string. if any condition is not met, it returns 0. the formula for that cell is

=IF(SUM(AA2:AA4)=0,SubItem,0)

where aa2:aa4 are the conditions which must be 0 to return a string and subitem is a named cell range.

Once it returns a string, I have a module to paste the cell aa5 onto a different sheet export. The problem is that after I run the routine, (it takes about 20 min) I find 0 values in the export sheet.

I have tried manually changing all the variables to the condition that created the error and none appears. I’ve also tried running through the code line-by-line and can’t seem to replicate it there either.

My last straw was inserting in the module that pastes into export sheet

If Worksheets("analysis").Range("aa5").Value = 0 Then
Exit Sub

And still I have 0 values after running!

I am not really a programmer but I have some experience with VBA code, is it possible I’ve created a race condition where the 0 is copied before the if is updated but it still passes the vba check?

How to&Answers:

Try to calculate your value before using it in VBA:

With Worksheets("analysis").Range("aa5")
    .Calculate
    If .Value <> 0 Then
        Worksheets("export").Range("A1").Value = .Value
    End If
End With