A menudo, necesita realizar varias acciones diferentes en el mismo objeto. Por ejemplo, puede que necesite establecer varias propiedades o ejecutar varios métodos para el mismo objeto.
Para establecer varias propiedades para el mismo objeto
* Una forma de hacerlo es crear varias instrucciones utilizando la misma variable de objeto, como en el código siguiente:
Private Sub UpdateForm()
Button1.Text = "OK"
Button1.Visible = True
Button1.Top = 24
Button1.Left = 100
Button1.Enabled = True
Button1.Refresh()
End Sub
Sin embargo, este código se puede escribir y leer con más facilidad mediante la instrucción With...End With, como en el código siguiente:
Private Sub UpdateForm2()
With Button1
.Text = "OK"
.Visible = True
.Top = 24
.Left = 100
.Enabled = True
.Refresh()
End With
End Sub
También se pueden anidar instrucciones With...End With situándolas una dentro de la otra, como en el código siguiente:
Sub SetupForm()
Dim AnotherForm As New Form1()
With AnotherForm
.Show() ' Show the new form.
.Top = 250
.Left = 250
.ForeColor = Color.LightBlue
.BackColor = Color.DarkBlue
With AnotherForm.Textbox1
.BackColor = Color.Thistle ' Change the background.
.Text = "Some Text" ' Place some text in the text box.
End With
End With
End Sub
Sin embargo, en la instrucción anidada With, la sintaxis hace referencia al objeto anidado; las propiedades del objeto en la instrucción With externa no están establecidas. |