Exit While Loop in VBScript / Trim Return Carriage and Tab


VBScript is not perfect but it is still good enough. Today I have come across two problems and learned the workaround.

1. There is currently no ‘Exit While’ statement compared to ‘Exit For’. For example, if you want to break the while loop, such as following, you will have a “Microsoft VBScript compilation error: Invalid ‘exit’ statement” error.

1
2
3
4
5
6
7
Dim i: i = 1
While i < 100
    i = i + 1
    If i > 50 Then
        Exit While
    End If
Wend
Dim i: i = 1
While i < 100
 	i = i + 1
 	If i > 50 Then
		Exit While
	End If
Wend

The workaround is to use Do WhileLoop, and break the loop using Exit Do instead:

1
2
3
4
5
6
7
Dim i: i = 1
Do While i < 100
    i = i + 1   
    If i > 50 Then
        Exit Do
    End If
Loop
Dim i: i = 1
Do While i < 100
 	i = i + 1 	
 	If i > 50 Then
		Exit Do
	End If
Loop

2. The Trim function does not remove the carriage return i.e. CHR(13) + CHR(10) and tab. The correct way is to use following:

1
newstring = Trim(Replace(Replace(oldstring, vbCrLf, ""), vbTab, ""))
newstring = Trim(Replace(Replace(oldstring, vbCrLf, ""), vbTab, ""))

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
202 words
Last Post: VBScript Malware Demo using FileSystemObject
Next Post: VBScript Browse for Folder using Shell.Application Object

The Permanent URL is: Exit While Loop in VBScript / Trim Return Carriage and Tab

Leave a Reply