3
votes

I have a VBA macro in excel that has run fine for a while. I've been making changes with these loops already working and suddenly the code is not compiling:

Compile error: Wend without While

I have tried changing to Do While...Loop loops, but I got the equivalent

Compile error: Loop without Do

Here is the structure of my code:

'This loop is fine
While '(code for evaluation)
'code to run in loop
Wend

While '(more eval code)
'code
  While '(eval code)
  'code
  Wend '<--This is where the compile error occurs
  'code
  While '(eval code)
  'code
  Wend
'code
Wend

Does anyone have any idea what could be the issue? (Bonus: Does the indentation of code actually matter?)

2
The problem is usually caused by an IF without an equivalent END IF somewhere in the code. - Gary's Student
I suspect you're actually missing a closing statement for a block in the code you left out. For indentation, res ipsa loquitur. ;) - Rory
@Gary'sStudent That was it! I don't think this question is a duplicate (I couldn't find one) so please post an answer! - ZX9
Does the indentation of code actually matter? - No for the compiler. Yes for programmers. - Pankaj Jaju
For the love of code, extract methods and do something about these nested blocks! - Mathieu Guindon

2 Answers

7
votes

This message Wend without While usually indicates an un-terminated IF

Somewhere there may be an IF without the matching End If

(This kind of error message is a bit annoying since it hides the true error)

2
votes

The real problem is that you have a method that does too many things.

You can locate the mismatched code block, and fix it - but you'd be dismissing a readability issue with an "hey it works, leave it alone" excuse.

While
'code to run in loop
Wend

' **** move to another method
While 
'code

' **** move to another method
  While 
  'code
  Wend 

' **** move to another method
  'code
  While 
  'code
  Wend

'code
Wend

Extracting methods in VBA code can be a bit of a pain, because parameters and return values must be determined, and then the extraction point needs to be turned into a method/function call. Fortunately, there's a tool for that (disclaimer: I wrote it).