dcsimg
June 25, 2018
Hot Topics:

My Favourite Functions - Part 3

  • November 19, 2002
  • By Karl Moore
  • Send Email »
  • More Articles »

Static Variables

Few programmers seem to know what static variables are. Look at this code:

Private Sub Command1_Click()   Dim intCount As Integer   intCount = intCount + 1   MsgBox intCountEnd Sub

If you run this on a form with a command button called 'Command1', you'll find that every time you hit the button, the message box displays 1. That's because the intCount variables is killed off when the sub finishes running - and is recreated the next time you run it.

But if you change the 'Dim' part to 'Static', you'll notice it doesn't disappear - and the number keeps increasing every time you hit the command button. That's a static variable - it's rather like a public variable in that it remains 'alive' even though the sub has finished working - though no other bits of code can see it.

Cool, eh?

-- Julian Versace, Italy

The IIf Function

The IIf function is a very cool way of evaluating a bit of text without a dozen If-Then-Else-EndIf statements. Here's an example:

Dim blnTest As BooleanblnTest = TrueMsgBox IIf(blnTest = True, "Hello Mark!", "Hello John!")

Here, the IIf function asks if the blnTest variable is equal to true. If it is, it would returns the first string ("Hello Mark!") - if not, it returns the second ("Hello John!")

So you use IIf like this:

x = IIf (ExpressionToEvaluate, TruePart, FalsePart)

This can be very useful. I also noticed an article on VB-World.net about it here.

-- Ken Carbrook, Yorkshire

Phew! That concludes our epic three part tips series. For more top Visual Basic code snippets, please check out the comprehensive tips library here.





Page 5 of 5



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.

Sitemap

×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date