How-To... - Using the With Statement

I was making updates to my program, and I was altering lots of properties of objects on a form on my main form, which mean I had to type frmStarup.chkStartup.Enabled=True and frmStartup.chkStartup.Value=1 and as you can guess, this made typing the same thing over and over again. Then, I remembered seeing the With Statement in the VB Help, and I thought it would come in handy. Before I go on, the syntax for the With Statement is as follows:-

With object

[statements]

End With

The statement allows you to alter properties of an object without having to type in the full 'path'.(As above). For example, I changed my long lines into this statement and now it looks like this :-

With frmStartup.chkStartup

.Enabled = True ' You always need . at the beginning of each line
.Value = 1 'with in the With Statement

End With

As you can see, this made it not so much to type, and also makes the code much tidier. But thats not all it can do, instead of using an object on a form, chkStartup on frmStartup, you can use the form as the object. In my program, I also had to show a form, enable a command button and do the above with the check box. So I altered the With Statement to look like this :-

With frmStartup

.Show ' Shows the form...
.cmdCancel.Enabled = True 'Enables the command button...
.chkstartup.Enabled = True 'Enables the check box...
.chkstartup.Value = 1 'Gives the check box a value of 1...

End With

Again, this makes less to type in, and overall makes the code alot tidier. Use this With statement whenever you can, especially when altering the properties of objects on other forms.


This site is Copyright © 1999 of David Cowan. VB How-To, Dodgesoft and DodgeSoft Productions is Copyright © 1999 of David Cowan. Source-code and programs are copyright of their respective owners. For a messageboard, click here