January 27, 2021
Hot Topics:

My Favourite Functions - Part 3

  • 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

This article was originally published on November 20, 2002

Enterprise Development Update

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

Thanks for your registration, follow us on our social networks to keep up-to-date