2009-06-17

VBscript: progress bar function

I am from time to time writing small VBscripts that doe some kind of repeating task and wanted to make some nice progress bar to show the progress. I came up with this function:
' Copyright (c) 2009 Rune Nordbøe Skillingstad 
'
' This program is free software; you can redistribute it and/or modify
' it under the terms of the GNU General Public License as published by
' the Free Software Foundation; version 2 dated June, 1991.
'
' This program is distributed in the hope that it will be useful, but
' WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
' General Public License for more details.
'
' You should have received a copy of the GNU General Public License
' along with this program; if not, write to the Free Software
' Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
' USA.


Option Explicit

On Error Resume Next

Dim
i

For i = 1 To 1000
Progress 1000, i
Next

Function Progress(max,prog)
Dim length, t, x
length = 68
t = int(length * (prog/max))
WScript.StdOut.Write vbCr & "|"
For x = 0 To t
WScript.StdOut.Write "-"
Next
If
t < length Then
For
x = (t + 1) To length
WScript.StdOut.Write " "
Next
End If

WScript.StdOut.Write "| " & FormatPercent(prog/max)
If t = length Then
Wscript.StdOut.WriteLine
End If
End Function


The code includes a "sample" for 1000 iterations:



If you are running a high number of iterations, you might want to reduce the frequency of the redrawing of the progress bar, as it will consume unwanted CPU cycles. A quick way of doing this, is to use a a modulo on the iterator counter. This example will only redraw the progress for each 10th iteration (1000/100 = 10)
max = 1000
modulo = int(max / 100)
For
i = 1 To max
If (i Mod modulo) = 0 Then
Progress max, i
End If
Next

1 comment:

  1. THANKS MAN!
    It works like a sharm here. I love you! hehe.
    Just, thanks, that was very useful for me.
    I'm starting programming in VBScript and your post was very useful.

    ReplyDelete