Everyone knows DoEvents takes forever if you're doing anything lengthly with it(adding a large amount of items to a listbox, for example). But it lets you do other tasks, so it's great in that respect.

But let's say you want a label to be a real-time display of items being added to the listbox(like a counter), but you're adding a large number of items to the listbox and you don't want it to take FOREVER. There's a way around it, and it's very simple. I'm sure a lot of people already know about this, but for the folks who don't(possibly new to VB), this will let you have the best of both worlds with DoEvents:

VB Code:
  1. Public Function sysDoEventsIf(doIf As Integer, isDivisibleBy As Integer) As Boolean
  2.  
  3.     On Error GoTo endWithoutEvents
  4.    
  5.     If doIf = 0 Then GoTo endWithoutEvents
  6.     If doIf < isDivisibleBy Then GoTo endWithoutEvents
  7.        
  8.         Dim divisResult As Integer
  9.         divisResult = (doIf / isDivisibleBy)
  10.            
  11.             If divisResult < 1 Then GoTo endWithoutEvents
  12.                 If InStrB((doIf / isDivisibleBy), ".") > 0 Then GoTo endWithoutEvents
  13.                    
  14.                     sysDoEventsIf = True
  15.                     DoEvents
  16.                
  17. endWithoutEvents:
  18.  
  19. End Function



What does that do? It checks if the variable you specify is equally divisible by anothe specified number, and then ONLY does "DoEvents" if it is. How is that useful? Here's an example:

VB Code:
  1. Private Sub Command1_Click()
  2.    
  3.     Dim d As Boolean
  4.     Dim i As Integer
  5.    
  6.     For i = 0 To 24999
  7.         d = sysDoEventsIf(i, 100)
  8.         List1.AddItem "Item " & i, i
  9.             If d = True Then Label1.Caption = "Items: " & List1.ListCount
  10.     Next i
  11.    
  12.     Label1.Caption = "Items: " & List1.ListCount
  13.  
  14. End Sub



This button(Command1) adds 25,000 items to a listbox. The kicker is it will only call DoEvents to free up the process if the current step(defined as "i") is divisible by 100. So rather than calling DoEvents on EVERY step(making the process take a lot longer), it will only call it every 10 steps!

You can make it call DoEvents as often as you want. Change the function call to "d = sysDoEventsIf(i, 1000)" and it will only call DoEvents if the current step integer is divisible by 1000 evenly.



NOTE: The larger the number you're trying to divide it by, the quicker it goes. The smaller the number you're trying to divide it by, the slower it will go.



Hope this helps some folks with... whatever.



-Brendan