The With...End With Mini-Lecture

Take this code (please!...;-):

txtFirstName="Karla"
txtFirstName.Forecolor=vbWhite
txtFirstName.BackColor=vbBlack

Looks okay, right? Well, it's slow. It's like if you were at work and your boss called you into the her office. "There's a new dress code and you need to start wearing purple spandex. That's all; you can go now." Ooookaaayyy, you think. Whatever. You go back to your cubicle.

Five minutes later you get called into her office again: "oh, and you also have to wear those high-heeled Spice Girls tennis shoes. That's all; you can go now." Back to your cubicle you go, wondering what new and interesting substance must be in the executive water cooler.

But, wait! She wants you back again: "I forgot to tell you, you also have to wear a propeller beanie. Bye." Bye, indeed. That resume needs some polishing. Dilbert is real!!

If we coded this situation it might look something like this:

employee.clothing="purple spandex"
employee.footwear="high-heeled Spice Girls Tennies"
employee.headgear="propeller beanie"

Wouldn't it have been much more efficient if your boss had called you into her office just once to tell you all about the new dress code? Something along the lines of:

With employee
   .clothing="purple spandex"
   .footwear="high-heeled Spice Girls Tennies"
   .headgear="propeller beanie"
End With

Well, that's why in VB we have the With...End With construct. When you refer to an object over and over again it's like you pick it up and put it down and then pick it up and put it down, etc. Much better to pick it up, deal with it fully and then put it back down. Our first example could better be written:

With txtFirstName
   .text="Karla"
   .Forecolor=vbWhite
   .BackColor=vbBlack
End With

Ken Getz, a well-known VB/Access guy, ran some tests that showed the With construct to be 3000% faster than non-With. We're talking milliseconds here, but sometimes every little bit counts.



Internet Content Rating Association Valid XHTML 1.0! Valid CSS!

Alrak's Course Resources ©2002-2022 Karla Carter. All rights reserved. This material (including, but not limited to, Mini-lectures and Challenge Labs) may not be reproduced, displayed, modified or distributed without the express prior written permission of the copyright holder. For permission, contact Karla.