A UserForm with Movable Controls


I'm not sure of the practical significance of this technique, but the example in this section will help you understand mouse- related events. The UserForm shown in Figure 15-13 contains three Image controls. The user can use the mouse to drag these images around in the dialog box.

image from book
Figure 15-13: The three Image controls can be dragged and rearranged by using the mouse.
CD-ROM  

This example is available on the companion CD-ROM. The file is named image from book  move controls.xlsm .

Each of the Image controls has two associated event procedures: MouseDown and MouseMove . The event procedures for the Image1 control are shown here (the others are identical except for the control names ).

 Private Sub Image1_MouseDown(ByVal Button As Integer, _     ByVal Shift As Integer, ByVal  As Single, ByVal Y As Single) '   Starting position when button is pressed     OldX = x     OldY = Y     Image1.ZOrder 0 End Sub Private Sub Image1_MouseMove(ByVal Button As Integer, _     ByVal Shift As Integer, ByVal  As Single, ByVal Y As Single) '   Move the image     If Button = 1 Then         Image1.Left = Image1.Left + (X - OldX)         Image1.Top = Image1.Top + (Y - OldY)     End If End Sub 

When the mouse button is pressed, the MouseDown event occurs, and the — and Y positions of the mouse pointer are stored. Two public variables are used to keep track of the original position of the controls: OldX and OldY . This procedure also changes the ZOrder property, which puts the image "on top" of the others.

When the mouse is being moved, the MouseMove event occurs repeatedly. The event procedure checks the mouse button. If the Button argument is 1, it means that the left mouse button is depressed. If so, then the Image control is shifted relative to its old position.

Also, notice that the mouse pointer changes when it's over an image. That's because the MousePointer property is set to 15 - fmMousePointerSizeAll . This mouse pointer style is commonly used to indicate that something can be moved.




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