Centering A Form On The Screen

  1. Set the StartUpPosition property for the form to 2 - CenterScreen.

This code will cause entering msgbox and inputbox statements into any of the form's events to display the dialog box in the center of the screen.

Centering a Control Horizontally
On A Form

  1. In the active or load event for the form with the control enter the following code
    x.Move (Me.Width - x.Width) / 2
    replacing x with the name of the control.

Should you want to center it vertically too (would probably produce  undesired results) add
(Me.height - x.Height) / 2
after the above code replacing x with the name of the control.

Note if the form is to be loaded maximized you will need to replace the word Me with Screen to avoid having the buttons become centered within the design time dimensions of the form.

Horizontally Centering Two Side By Side Controls On A Form

  1. In the general section of the form with the controls enter the following code:

    Sub CenterControls(LeftControl As Control, RightControl As  Control)

    `define variables
    Dim NewLeft1 As Double
    Dim NewLeft2 As Double
    Dim Width1 As Double

    `center both controls individually on the form
    `if sub routine ended here 2nd control would be on top of 1st
    LeftControl.Move (Me.Width - LeftControl.Width) / 2
    RightControl.Move (Me.Width - RightControl.Width) / 2

    intialize variables
    Width1 = LeftControl.Width
    NewLeft1 = LeftControl.Left
    NewLeft2 = RightControl.Left

    `loop until the stored left value for the left control + its stored
    `width equals the stored left value for the right control
    Do Until NewLeft1 + Width1 = NewLeft2 - 1
          `decrement the stored left value for the left control by 1
          NewLeft1 = NewLeft1 - 1
         
          `increase the stored left value for the right control by 1
          NewLeft2 = NewLeft2 + 1
    Loop

    `change the controls left values to the new stored left values
    LeftControl.Move (NewLeft1)
    RightControl.Move (NewLeft2)
    End Sub

    Note: Do not change the subroutine to have the actual left values updated in the loop in place of the variables as this will  result in the controls movement being visible on screen along with flickering unless the controls are made invisible during the operation.
     
  2. In the active or load event for the form with the control enter the following code:

    call CenterControls(l, r)

    replacing l with the name of the control on the left in the pair and r with the control on the right  in the pair.)

Lila Godel's Web Site
Brought To You By Hamilton Services, Inc.

Contact Me

Access

Access

Home

Home

Links

Links

Miscellaneous

Other

Programs By Me

Programs

Visual Basic

Visual Basic

Windows

Windows