Sunday 3 January 2010

Using 'With/End With' Statements

Instead of referencing the full name of a control for example we can use the With/End With statement. This allows us to reduce what we have to type if we anticipate that we will make many references to the control and it's routines.

The learning objective is to learn how and why the With/End With statement is used.

You might be referencing a textfield  in part of a statement as follows:

If Is Numeric(txtField.Text) Then
  txtField.Focus
  txtField.SelectionStart = 0
  txtField.SelectionLength = txtField.Text.Length
  Messagebox.Show("Value in text field must not be numeric.")
End If

But instead you could say:

With TxtField
If Is Numeric(.Text) Then
  .Focus
  .SelectionStart = 0
  .SelectionLength = .Text.Length
  Messagebox.Show("Value in text field must not be numeric.")
End If
End With

Notice how we do not need to reference the txtField now as we have said 'With TxtField'?

Can you see the dot (.) then the name such as Text, without the control's references i.e. TxtField? Because we have used the With statement we do not need to keep referring to the TxtField control.

This allows us to cut down significantly on the amount of typing we have to do when creating statements that refere to controls or other objects.

No comments:

Post a Comment