Home » excel » excel – Using Null (or something else) to avoid 'Out of Memory'

excel – Using Null (or something else) to avoid 'Out of Memory'

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have this snippet of code that will highlight select rows of data within a table different colors based on varying parameters:

Public Sub HighlightRecentSampleRequests()

Dim sht As Worksheet
Dim LastRow As Long
Dim cell As Range
Dim dt, txt

Set sht = Worksheets("Sample Transfer Log")
LastRow = sht.Cells(Rows.Count, "A").End(xlUp).Row

For Each cell In sht.Range("K3:K" & LastRow).Cells
    dt = cell.Value
    txt = cell.Offset(0, -3).Value
If dt >= Date - 7 And txt = "Sample Receipt" Then
    cell.Range("A1:P1").Offset(0, -10).Interior.ColorIndex = 45 'orange
ElseIf dt >= Date Then
    cell.Range("A1:P1").Offset(0, -10).Interior.ColorIndex = 6 'yellow
Else
    cell.Range("A1:P1").Offset(0, -10).Interior.Color = RGB(220, 230, 242) 'default color
End If
Next

End Sub

I made an alteration to my original code to produce the above to make it do what I wanted. Now I am receiving the ‘Out of Memory’ message constantly when I run my system. This seems to be due to the last portion of the If statement where all cells that do not meet the previous criteria will be highlighted as the default color. I attempted to refer to the range using a variable and then setting that variable to ‘Nothing’ after completing its use, but that returned a message of ‘Invalid Use of Null’ and thereafter those variables were useless and needed to be deleted for the code to work again.

Basically, I would like to get rid of the ‘Out of Memory’ message without screwing up my entire code.

How to&Answers:

After looking at the actual file besides your code processing a Range which varies and is being called by an UserForm it is not the direct cause of the memory issues.

Because there are multiple UserForms which are being loaded into memory when .Show is used (for the specific UserForm). They do not get released from memory by using .Unload after the UserForm is processed but stay active in the background and taking up memory space.

By properly using .Unload after having processed an UserForm and .Load or .Show the UserForm when needed again memory is freed up properly.

Answer:

You could try using case statements. Something like this.

    Select Case dt
        Case Is >= Date - 7
            If txt = "Sample Receipt" then
                cell.Range("A1:P1").Offset(0, -10).Interior.ColorIndex = 45 'orange
            End If
        Case Is >= Date
            cell.Range("A1:P1").Offset(0, -10).Interior.ColorIndex = 6 'yellow
        Case Else
            cell.Range("A1:P1").Offset(0, -10).Interior.Color = RGB(220, 230, 242) 'default color
    End Select