I wrote a macro that would loop through a string and trim out all non-numeric characters. I ran into an issue where the last loop cycle would pass a null string to if not isnumeric() resulting in true, causing the string to attempt to replace that character.
Here is what the code accomplishes when inserted to a range loop:
Here is the original code:
L = Len(s)
i = 0
While i <= L
i = i + 1
If Not (IsNumeric(mid(s, i, 1))) Then
s = Replace(s, mid(s, i, 1), "")
i = i - 1
L = Len(s)
End If
Wend
You'll notice that whenever I delete a character from the string, I reduce the i counter by one. This is because if there are multiple non-numeric characters in a row, and I delete character #2, char #3 becomes the new char #2. So I needed the loop to go back and check that index number over again until it's a number, or the string is finished.
Well that created a problem: I ended up with an infinite loop because the last iteration passes a null string into that statement, and it keeps running the i-1
This problem persisted with both a while i <= L and with a for i = 1 to L
I found that I can include the conditional i <= L in the If statement, and it would then prevent the last iteration from reaching that point and causing an infinite loop. The working code is below:
L = Len(s)
i = 0
While i <= L
i = i + 1
If Not (IsNumeric(mid(s, i, 1))) And i <= L Then
s = Replace(s, mid(s, i, 1), "")
i = i - 1
L = Len(s)
End If
Wend
Can anyone explain why my For or While Loops ended up looping once again with an i greater than my L?