Example of Turtle Graphics Library for Excel VBA by using GDI32 Instructions
Procedure
- Copy the source program of graphics drawing library by GDI32 instructions and paste to Module 2.
- Insert a user form. The size of the user form should be larger than Viewport.
- Fill in the procedure for displaying the form on the workbook
Private Sub Workbook_Open() UserForm1.Show End Sub
- Insert buttons into Form
- Write a CALL statement for displaying turtle graphics in the CommandButton1_Click procedure.
Private Sub CommandButton1_Click() ' Draw polygons TurtleTest01 End Sub Private Sub CommandButton2_Click() ' Draw Spirals TurtleTest02 End Sub Private Sub CommandButton3_Click() ' Koch curve DrawKochCurve End Sub Private Sub CommandButton4_Click() ' Tree Diagram DrawTree End Sub Private Sub CommandButton5_Click() SetViewPort 0, 0, 699, 629 gClear End Sub
- Fill in Module 1 with procedures to obtain device context and display turtle graphics.
Get device context and display turtle graphics.
Option Explicit Sub TurtleTest01() ' Get device context handle monhdc = GetForegroundWindow() myhdc = GetDC(monhdc) If myhdc = 0 Then Exit Sub Dim i, j, side InitializeTurtleGraphics side = 100 For i = 3 To 9 For j = 1 To i TGMoveL side TGTurn 360 / i Debug.Print gTGCurrentX, gTGCurrentY Next j Next i End Sub Sub TurtleTest02() ' Get device context handle monhdc = GetForegroundWindow() myhdc = GetDC(monhdc) If myhdc = 0 Then Exit Sub Dim length, angle, d InitializeTurtleGraphics length = 300 angle = 89 d = 2 TGSetPoint 600, 0 Do While length > d TGMoveL length TGTurn angle length = length - d Loop End Sub Sub DrawKochCurve() ' Get device context handle monhdc = GetForegroundWindow() myhdc = GetDC(monhdc) If myhdc = 0 Then Exit Sub Dim i, length, n n = 4 ' Koch Dimension length = 5 ' 0-th length InitializeTurtleGraphics For i = 1 To 3 Koch n, length TGTurn -120 Next i End Sub Sub Koch(n, length) If n = 0 Then TGMoveL length Else Koch n - 1, length TGTurn 60 Koch n - 1, length TGTurn -120 Koch n - 1, length TGTurn 60 Koch n - 1, length End If End Sub Sub DrawTree() ' Get device context handle monhdc = GetForegroundWindow() myhdc = GetDC(monhdc) If myhdc = 0 Then Exit Sub Dim myLength, myTurn, myRatio myLength = 200 ' 0-th branch length myTurn = 60 ' Angle of bending myRatio = 0.6 ' Ratio of Branch length InitializeTurtleGraphics TreeAll myLength, myTurn, myRatio End Sub Sub TreeAll(myLength, myTurn, myRatio) If myLength < 5 Then Exit Sub TGMoveL myLength, vbGreen TGTurn -myTurn TreeAll myLength * myRatio, myTurn, myRatio TGTurn myTurn TGTurn myTurn TreeAll myLength * myRatio, myTurn, myRatio TGTurn -myTurn TGMoveL -myLength, vbGreen End Sub
Download Excel file tg-gdi32-eng.xlsm
It contains the programs for display of polygons, spairals, Koch curves and Tree diagrams.