0
votes

So I've been trying to make a macro for Microsoft Word for fun recently, but I've hit a bit of a roadblock. What I'm trying to do is actually just to cover the entire page in shapes, but not have them overlap. Currently, the shapes just end up going in a straight line between the top left and bottom right corners, nowhere else, and constantly overlap. I was wondering if there's anyway to accomplish the shapes being on the whole page without overlapping? My script is:

Sub Wait(n As Long)
    Dim t As Date
    t = Now
    Do
        DoEvents
    Loop Until Now >= DateAdd("s", n, t)
End Sub

Sub Pause()
    Wait 0.1
End Sub

Sub Test()
    Dim shpCanvas As Shape
    Dim shpCanvasShapes As CanvasShapes
    Dim shpCnvItem As Shape

    ShapeSize = 250 * Rnd() + 250
    Set shpCanvas = ActiveDocument _
                    .Shapes.AddCanvas(Left:=ShapeSize, Top:=ShapeSize, _
                                      Width:=50, Height:=75)
    Set shpCanvasShapes = shpCanvas.CanvasItems

    With shpCanvasShapes
        .AddShape Type:=msoShapeIsoscelesTriangle, _
                  Left:=0, Top:=0, Width:=50, Height:=50
        .AddShape Type:=msoShapeOval, _
                  Left:=10, Top:=25, Width:=30, Height:=10
        .AddShape Type:=msoShapeOval, _
                  Left:=20, Top:=25, Width:=10, Height:=10
    End With
    Pause
End Sub

Thanks a bunch, Xander

2

2 Answers

0
votes

Here's an idea, but it might not be easy to code. Define an array that's 34 by 44, or one value for each quarter-inch square on the page. Start with the array filled with False.

Generate a random shape and a random position. Calculate which quarter-inch squares the shape would cover. Check whether there is a False value in the array for all of those quarter-inch squares.

  • If all are False, then add the shape to the Word document. Put True values in the array for every quarter-inch square that is covered by the shape.

  • If any are True, then generate another shape and repeat the test.

Stop the macro when 100 shapes have been generated without being added to the Word document.

0
votes

You need a better algorithm. The reason they start at the top left and go to the bottom right is this line of code:

.Shapes.AddCanvas(Left:=ShapeSize, Top:=ShapeSize, _
                                      Width:=50, Height:=75)

In the above, you are setting the Left proportional to Top (in this case, actually equal because you use ShapeSize each time), so there is a linear function.

You can progress with the randomness of the generation of the shape, or you can randomly select a space on the page (basing your randomness on remaining space, rather than the whole page) and then fit one of your random shapes into that space.

I will leave this as an exercise for yourself in coding that algorithm, but it should not be too hard to generate.