Search code examples
vbaexcellarge-data

Excel VBA method fails to run and returns no error


I intended my code to search through an excel spreadsheet filled with data and return entire rows whose p-values were below 0.05. But, I do not receive any syntax errors and the code looks about right. I am working with a large data set, ~780000 row entries so I don't know if this is what's resulting in an error. The code is supposed to read through and if the aforementioned condition is met, return the entire row, else the row is supposed to be ignored. Here, the code returns nothing and provides no error.

Sub GrabRelaventData()
    Dim i As Long, j As Long
    Dim s1 As Worksheet, s2 As Worksheet
    Set s1 = Sheets("RNASeq EH developmental 10 hits")
    Set s2 = Sheets("pVal checks")
    For i = 1 To 787731
        If s1.Cells(i, 10) > 0.05 And s1.Cells(i, 16) > 0.05 And s1.Cells(i, 22) > 0.05 And s1.Cells(i, 26) > 0.05 Then
            Exit For
        Else
            For j = 1 To 39
                s2.Cells(i, j).Value = s1.Cells(i, j).Value
            Next j
        End If
    Next i
End Sub

Solution

  • Based on what you are doing, I think you've flipped your logic. Set your IF...THEN to what you want to do if the value is less than .05. If the value is greater, you will get to the NEXT and loop.

    When you use EXIT FOR, it does not go to the next loop, it figures you are done. Some languages (VB.net) have a Continue For statement, that would take you through the loop. Assuming the rest of your code is right, try this:

    Sub GrabRelaventData()
        Dim i As Long, j As Long
        Dim s1 As Worksheet, s2 As Worksheet
        Set s1 = Sheets("RNASeq EH developmental 10 hits")
        Set s2 = Sheets("pVal checks")
        For i = 1 To 787731
        'Flip your signs - you want to do something when the p-value is LESS THAN, 
    'not avoid doing something when it is greater than.
            If s1.Cells(i, 10) < 0.05 And s1.Cells(i, 16) < 0.05 And s1.Cells(i, 22) < 0.05 And s1.Cells(i, 26) < 0.05 Then
                '"Exit For" will take you to the next i - you want use the j loop if the condition is true.
           ' Else - No need for the else this way.
                For j = 1 To 39
                    s2.Cells(i, j).Value = s1.Cells(i, j).Value
                Next j
            End If
        Next i
    End Sub
    

    This assumes that you want ALL of the p-values to be < .05. If you wanted to act when ANY p-value was < .05 you would use an OR instead of an AND. Good Luck!