Wednesday, February 23, 2011

3D graphics animations in Excel


I have been once on the very boring meeting recently. If I had Internet connection on my notebook working I could entertain myself in other ways. But with nothing else but MS Office I opened Excel and tried making 3D surface chart with animation.

Here's how I did it step-by-step instructions:
·    Enter a couple of decreasing degree values and fill to the right
  • Enter a couple decreasing degree values vertically and fill to the bottom
  • On the row below convert degrees to radians with the formula =RADIANS(C1)
  • Do the same for the vertical row =RADIANS(A3) and fill the rest of the horizontal and vertical cells
  • The corner cell B2 will contain the phase component of the surface formula, put zero there for now.
  • In the cell C3 enter the formula for the surface point =SIN($B3*C$2+$B$2)
    This formula takes a sin of the radian value above the current cell multiplied with a radian value on the left of the cell, adds a phase component (used for animation).
  • Fill the rest of the sheet with the same formula. Note that dollar signs in the formula which makes copy/paste operation to keep (!) the cell address prefixed with the dollar sign even though usually the formula which is shifted is having its arguments shifted as well. This makes sure we a locked to the B column (vertical radian values) and 2nd row (horizontal radian values).
  • Select all the points and make a surface chart. You should get the static 3D function graph similar to mine.
As for animating, remember the zero at $B$2? If you change it to 0.1 for example, you may notice the chart has moved a little bit. We only need to make it move automatically now.
  • Create a new macro and start editing it.
·         Enter the following into the selected macro:

    PauseTime = 15    ' Set duration.
    Start = timer    ' Set start time.
    Do While timer < Start + PauseTime
        Range("B2").Value = Range("B2").Value + 0.15
        DoEvents    ' Yield to other processes.
    Loop

This code is running for 15 seconds repeatedly adding 0.15 to the value in the B2 cell, which makes the 3D chart move a frame. DoEvents() is allowing Excel to redraw the chart, without it the cell value will increase but Excel will not have time to paint the new chart.
  • Assign a shortcut key (like Ctrl-A) to run this macro easily. And press the shortcut to test.
  • You may want to play around with another formula: =SIN($B19+$B$2)*COS(E$2+$B$2*2)

No comments: