Counting loops and Ifs in a piece of code (Resolved)
hi everyone
Im quite new to vb so please bear with me.
What I would like to do is write a piece of vb code
which will read in another piece of vb code line by line.
But it needs to be able to count how many occurances
of a loop and IF statements which appear in that code.
This must however ignore any IFs or similar words that
may appear in any comments or within a string.
Hope that makes sense.
So far ive managed to write a very simple piece of code
which counts the number of FORs, IFs, and WHILEs.
VB Code:
Dim strText As String
Dim intCounter1 As Integer
Dim intCounter2 As Integer
Dim intCounter3 As Integer
Open "C:\blah\blah\something.txt" For Input As #1
While Not EOF(1)
Line Input #1, strText
If InStr(strText, "End If") <> 0 Then
intCounter1 = intCounter1 + 1
End If
If InStr(strText, "Loop") <> 0 Then
intCounter2 = intCounter2 + 1
End If
If InStr(strText, "Wend") <> 0 Then
intCounter3 = intCounter3 + 1
End If
Wend
txtIf.Text = intCounter1
txtFor.Text = intCounter2
txtWhile.Text = intCounter3
txtTotal.Text = intCounter1 + intCounter2 + intCounter3
Close #1
End Sub
Thanks in advance for any advice or tips.
Re: Counting loops and Ifs in a piece of code
Here's a slight modification
VB Code:
'...
Do While Not EOF(1)
Line Input #1, strText
'Remove spaces on either side of the text, and convert to uppercase
'(easier to check it safely)
strText = Ucase(Trim(strText))
'Make sure it's not a comment
If Left(strText,1) <> "'" And Ucase(Left(strText,4)) <> "REM " Then
'Using InStr allows the text to be part of a string, left makes sure its the
'first part of the line (after the spaces, which we've removed already)
If Left(strText, 3) = "IF " Then
intCounter1 = intCounter1 + 1
End If
'these are a little more awkward, since they may or may not have code after
'(eg: "Loop" is valid, so is "Loop While x=1")
If Left(strText,5) = "LOOP " or strText = "LOOP" Then
intCounter2 = intCounter2 + 1
End If
If Left(strText,5) = "WEND " or strText = "WEND" Then
intCounter3 = intCounter3 + 1
End If
End If
Loop '(I dont like Wend, can't remember why!)
txtIf.Text = intCounter1
'...
this doesn't take into account the problem of using : to combine multiple lines of code onto one line, but it's a little better ;)