A Puzzle on a UserForm


The final example in this chapter is a familiar sliding puzzle, displayed on a UserForm (see Figure 15-28). This puzzle was invented by Noyes Chapman in the late 1800s.

image from book
Figure 15-28: A sliding tile puzzle in a UserForm.

The goal is to arrange the shuffled tiles ( CommandButton controls) in numerical order. Click a button next to the empty space, and the button moves to the empty space. The ComboBox control lets the user choose from three configurations: 3x3, 4x4, and 5x5. The New button shuffles the tiles, and a Label control keeps track of the number of moves.

This application uses a class module to handle all the button events (see "Handling Multiple UserForm Controls with One Event Handler," earlier in this chapter).

The VBA code is rather lengthy, so it's not listed here. Here are a few points to keep in mind when examining the code:

  • The CommandButton controls are added to the UserForm via code. The number and size of the buttons are determined by the ComboBox value.

  • The tiles are shuffled by simulating a few thousand random clicks on the buttons. Another option is to simply assign random numbers , but that would result in some unsolvable games .

  • The blank space is actually a CommandButton with its Visible property set to False .

  • The class module contains one event procedure ( MouseUp ), which is executed whenever the user clicks a tile.

  • When the user clicks a CommandButton tile, its Caption is swapped with the hidden button. No buttons are actually moved.

CD-ROM  

This workbook, named image from book  sliding tile puzzle.xlsm , is available on the companion CD-ROM.




Excel 2007 Power Programming with VBA
Excel 2007 Power Programming with VBA (Mr. Spreadsheets Bookshelf)
ISBN: 0470044012
EAN: 2147483647
Year: 2007
Pages: 319

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net