
ARCHIVE: TIPS & TRICKS
The With...End With statement
John Smiley 08.01.2000
Rating: -3.43- (out of 5)




The With...End With statement
In my consulting practice, I frequently see examples of Visual Basic
code that could be improved upon, either from a readability point of
view or from an efficiency point of view. Today I'd like to discuss a
relatively new Visual Basic construct that can improve both the
readability and efficiency of your code -- and save you quite a few
keystrokes in the process. That construct is the With...End With
statement.
The With...End With statement allows you to 'bundle' Property and Method
calls to a single object within the With...End With block. For instance,
here's some code that sets the properties of a Command Button, and then
executes its Move Method.
Private Sub Form_Load()
Command1.Caption = "OK"
Command1.Visible = True
Command1.Top = 200
Command1.Left = 5000
Command1.Enabled = True
Command1.Move 1000,1000
End Sub
By using the With...End With statement, we can eliminate quite a few
programmer keystrokes, and make the code a bit more readable in the
process -- like this...
Private Sub Form_Load()
With Command1
.Caption = "OK"
.Visible = True
.Top = 200
.Left = 5000
.Enabled = True
.Move 1000,1000
End With
End Sub
Not only have we reduced the number of keystrokes in the procedure, but
using the With...End With construct produces more efficient code.
Each reference to an object's property or method requires a Registry
'look up' to execute the code statement -- by using the With...End With
statement, VB is able to 'pool' this lookup into a single Input Output
operation -- thereby making your program run faster.
The bottom line -- whenever you find yourself coding multiple
operations against an Object, use the With...End With statement.
********************************************************************
Written by John Smiley, MCP, MCSD and MCT, author, and adjunct
professor of Computer Science at Penn State University in Abington,
Philadelphia University, and Holy Family College. John has been
teaching computer programming for nearly 20 years.
John Smiley is president of Smiley and Associates,
http://www.johnsmiley.com/smass/smass.htm a computer consulting firm
located in New Jersey.
 |

|
|
 |
|
 |