VBA – Animation with Excel

Animation consists of some pictures. In general, there are about 24 pictures per second, in order to do the “magic”. This could be easily automated with Excel, using Application.Wait (Now + #12:00:01 AM#), if we agree to make it a bit old-fashioned, with 1 picture per second.

So, in general, we are having four pictures, that are simply following each other with 1 second in between them:

Here is the code, that generates these 4 pictures and make them loop as much as we want them:

Sub TestMe()
    
    Dim cnt As Long    
    For cnt = 1 To 6        
        Wait1Second
        WriteCircle 15, 1, 1
        Wait1Second
        WriteCircle 15, 1, 2
        Wait1Second
        WriteCircle 15, 2, 1
        Wait1Second
        WriteCircle 15, 2, 2
    Next cnt
    
End Sub

Sub Wait1Second()
    Application.Wait (Now + #12:00:01 AM#)
End Sub

Sub WriteCircle(sizeX As Long, stepX As Long, stepY As Long)

    Dim sizeY As Long: sizeY = sizeX
    Dim y&, x&, r&, g&, b&
    Dim myCell As Range    
    Worksheets(1).Cells.Clear    

    For x = 1 To sizeX Step stepX
        For y = 1 To sizeY Step stepY
            With Worksheets(1)
                Set myCell = .Cells(x, y)
                
                If r >= 255 Then
                    If g >= 255 Then
                        b = b + 2
                    Else
                        g = g + 2
                    End If
                Else
                    r = r + 2
                End If                
                myCell.Interior.color = RGB(r, g, b)
            End With
        Next
    Next
    
End Sub

How does it work? Using the RGB system in the colors, first the R is increased from 0 to 255. Once the is up to 255, the is started to increase from 0 to 255. At the end, the B is increased from 0 to 255. The steps in the WriteCircle are the reasons to have spaces between the cells in Excel. They are called from WriteCircle 15, 1, 1   from the Sub TestMe(). The one with 2,2 is the one that results in an empty column and empty row.

In general, naming variables like Dim y&, x&, r&, g&, b& is stongly discouraged by anyone, but in this case, x is a great name for the horizontal axis of the coordinate system and in such a small example, r,g,b are quite ok for red, green and blue.