Vba end while ошибка

Asked
11 years, 2 months ago

Viewed
142k times

The code below is VBA for Excel. I am using the Visual Basic editor that comes with Excel 2007.

Dim counter As Integer
counter = 1
While counter < 20
    counter = counter + 1
end while '<- the compiler is complaining about this statement

The code doesn’t compile. Above the code I have only declarations. According to MSDN this should work but it doesn’t. What has happened?

Community's user avatar

asked Mar 16, 2012 at 7:53

1

While constructs are terminated not with an End While but with a Wend.

While counter < 20
    counter = counter + 1
Wend

Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can’t just assume that the documentation for the one can be applied directly to the other.

Also in the VBA help file:

Tip The Do...Loop statement provides a more structured and flexible way to perform looping.

answered Mar 16, 2012 at 8:29

Jean-François Corbett's user avatar

1

  1. Mar 26th, 2013, 06:11 AM


    #1

    sorenwrang is offline

    Thread Starter


    New Member


    Resolved [RESOLVED] Cannot end a while-loop. Error message

    Hi

    I get an error message when compiling the following code:

    REST = 10
    While REST >= 0.001
    REST = 0
    HJXS = XS
    XS = XS — (XS * XS * XS + AKS(2) * XS ^ 2 + AKM(3) * XS + AKM(4)) / (3 * XS ^ 2 + 2 * AKM(2) * XS + AKM(3))
    REST = REST + Abs(HJXS — XS)
    End While

    The error is: «Compile error: Expected: If or Select or Sub or Function or Property or Type or With or Enum or end of statement»

    I found the syntax for the while-loop on Microsoft’s webpage.. I really can’t see what is wrong. Note that I use no «Dim REST (…)» statement anywhere.. could this be an issue? I hope you can help me.

    Best regards,

    S�ren


  2. Mar 26th, 2013, 06:24 AM


    #2

    Re: Cannot end a while-loop. Error message

    Try

    vb Code:

    1. Dim REST As Integer, XS, HJXS

    2.   REST = 10

    3. While REST >= 0.001

    4.   REST = 0

    5.   HJXS = XS

    6.   XS = XS - (XS * XS * XS + AKS(2) * XS ^ 2 + AKM(3) * XS + AKM(4)) / (3 * XS ^ 2 + 2 * AKM(2) * XS + AKM(3))

    7.   REST = REST + Abs(HJXS - XS)

    8. Wend

    when you quote a post could you please do it via the «Reply With Quote» button or if it multiple post click the «»+» button then «Reply With Quote» button.
    If this thread is finished with please mark it «Resolved» by selecting «Mark thread resolved» from the «Thread tools» drop-down menu.
    https://get.cryptobrowser.site/30/4111672


  3. Mar 26th, 2013, 06:29 AM


    #3

    sorenwrang is offline

    Thread Starter


    New Member


    Re: Cannot end a while-loop. Error message

    Actually, replacing «End While» with «Wend» solved it.. I guess Microsoft should update their support pages :P .

    Thanks alot for helping !


  4. Mar 26th, 2013, 06:57 AM


    #4

    Re: [RESOLVED] Cannot end a while-loop. Error message

    You must have been looking at the wrong documentation. Here is the VB6 version.

    On Local Error Resume Next: If Not Empty Is Nothing Then Do While Null: ReDim i(True To False) As Currency: Loop: Else Debug.Assert CCur(CLng(CInt(CBool(False Imp True Xor False Eqv True)))): Stop: On Local Error GoTo 0
    Declare Sub CrashVB Lib «msvbvm60» (Optional DontPassMe As Any)


  5. Mar 26th, 2013, 10:24 PM


    #5

    Re: [RESOLVED] Cannot end a while-loop. Error message

    Quote Originally Posted by Bonnie West
    View Post

    You must have been looking at the wrong documentation.

    Searching for «Wend» in the «MSDN VS6.0 Library» return this example

    vb Code:

    1. Dim Counter

    2. Counter = 0   ' Initialize variable.

    3. While Counter < 20   ' Test value of Counter.

    4.    Counter = Counter + 1   ' Increment Counter.

    5. Wend   ' End While loop when Counter > 19.

    6. Debug.Print Counter   ' Prints 20 in the Immediate window.

    however, searching «While» returns

    vb Code:

    1. Dim Check, Counter

    2. Check = True: Counter = 0   ' Initialize variables.

    3. Do   ' Outer loop.

    4.    Do While Counter < 20   ' Inner loop.

    5.       Counter = Counter + 1   ' Increment Counter.

    6.       If Counter = 10 Then   ' If condition is True.

    7.          Check = False   ' Set value of flag to False.

    8.          Exit Do   ' Exit inner loop.

    9.       End If

    10.    Loop

    11. Loop Until Check = False   ' Exit outer loop immediately.

    in reference to do while. So I guess it is a matter of «do» or «not do».

    when you quote a post could you please do it via the «Reply With Quote» button or if it multiple post click the «»+» button then «Reply With Quote» button.
    If this thread is finished with please mark it «Resolved» by selecting «Mark thread resolved» from the «Thread tools» drop-down menu.
    https://get.cryptobrowser.site/30/4111672


  6. Mar 27th, 2013, 12:40 AM


    #6

    Re: [RESOLVED] Cannot end a while-loop. Error message

    While … End While is also valid but not in VB6


Конструкции

While завершаются не с помощью End While, а с Wend.

While counter < 20
counter = counter + 1
Wend

Обратите внимание, что эта информация легко доступна в документации; просто нажмите F1 . страница, которую вы ссылаетесь на, касается Visual Basic.NET, а не VBA. Хотя (нет каламбурования) существует некоторая степень перекрытия в синтаксисе между VBA и VB.NET, нельзя просто предположить, что документация для одного может быть применена непосредственно к другому.

Также в файле справки VBA:

Совет Оператор Do...Loop обеспечивает более структурированный и гибкий способ выполнения циклов.

In this article we will learn about some of the frequently asked Visual Basic programming questions in technical like “excel vba while… “end while” doesn’t work?” Code Answer. When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. Error handling in VBA is simple. An error message with filename, line number and a message describing the error is sent to the browser. This tutorial contains some of the most common error checking methods in Visual Basic. Below are some solution about “excel vba while… “end while” doesn’t work?” Code Answer.

excel vba while… “end while” doesn’t work?

'In VBA, there is no 'While... End While' loop.
'Attempting to use the above construct will result in a compile-time
'But VBA does have two loops that use the keyword, 'While'...
    'But VBA does not have an 'Exit While' statement.
'The 'Do Loop' can also be written as:      
'--------------------------------------------------------------------
'The loops can also run backward...
    'Do something with c here
    'Do something with c here

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don’t perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears
all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can’t be called in the same way Exit Sub can be, because the compiler doesn’t allow it.

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears.
Execution continues with the statement following the statement that
called the Sub procedure. Exit Sub can be used only inside a Sub
procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim’d) variables:

End Sub
Terminates the definition of this procedure.

Понравилась статья? Поделить с друзьями:
  • Vba byref ошибка
  • Vba autofill ошибка
  • Vba autocad обработка ошибок
  • Vba access ошибка 3265
  • Vba access обработка ошибок