Ошибка compile error expected end of statement

Compile error: Expected: end of statement

Introduction

Every programming language has its own grammar and vocabulary — technically known as syntax. Having a mastery of any language implies that you have a sound knowledge of its syntax.

As a beginner in VBA, you might be confronted with frustrating errors like the “Expected: end of statement” error. Be rest assured, no matter how experienced you’re with VBA coding, errors are always going to be a part of it.

The difference between a novice and an expert VBA programmer is that the expert programmers know how to effectively handle and use errors. This article will help you better understand the error above.

Types of errors in VBA

There are three types of errors in VBA: syntax errors, compile errors, and runtime errors.

Syntax Error

A syntax error, as you can guess from the name, occurs when VBA finds something wrong with the syntax in your code. When you type a line of code, VBA checks if the syntax is correct.

As soon as you hit enter, if VBA finds that something is missing in the syntax, it instantly shows a message with some text that can help you understand the missing part, as you can see in the screenshot below:

Compile error: Expected: Then or GoTo

Note: You need to enable the ‘Auto Syntax Check’ in the VBA option for the error dialog box to appear when there is an error. If not, VBA will only highlight the line without showing the error dialog box. The gif below shows you how to enable the error dialog box in VBA.

Step by step for how to enable the error dialog box

Compile Error

Compile errors occur when something is missing that is needed for the code to run. For example, in the code below, as soon as you run the code, it will show an error.

Compile error: Block if without End if

Note the difference between the syntax error and the compile error. The syntax error occurs even before you run the code and the font of the problematic line turns to red. The compile error occurs when you try to run the code and VBA identifies that something is missing.

Run Time Errors

Runtime errors are those that occur when the code is running. Run time errors will occur only when all the syntax and compile errors have been taken care of. They are not due to errors in the code itself, but rather due to factors external to the code — like a wrong input by the user, or an object that is not existing.

For example, if you run code that is supposed to activate an Excel worksheet, but that worksheet is unavailable (either deleted or its name changed), your code would give you a runtime error.

Unlike with the two previous errors, when a runtime error occurs, the message in the Run-time error dialog box is a little more explicit because it explains the problem and that can help you correct it.

Coming back to our specific error (“Expected: end of statement”), let’s write and run some code that will generate the error.

Step 1: Open the Visual Basic Editor and create a new module as seen in the gif below.

Creating a new module in Excel

Step 2: Write or copy and paste the following code:

Sub GenerateError()
Dim i As Integer = 5
End Sub

Before you even run the code, you will have the following result:

Compile error: Expected: end of statement

The error comes from the fact that two statements have been written in one line instead of two. The code should be:

Line 1: Dim i As Integer

Line 2: i = 5

Possible reasons for the “Expected: end of statement” error

From the types of errors in VBA described above, you must have guessed that the “Expected: end of statement” error is a syntax error. As such, the possible reasons for the error are as varied as the number of mistakes that you can make while writing a line of code.

Without being exhaustive, below is a list of possible reasons for that error:

1)    Writing two statements in one line (see the example above)

How to fix: Check to see if two different statements have inadvertently been put on the same line then send the second statement to a new line.

2)    Absence of parentheses

How to fix: Make sure you have parentheses (both open and close) where necessary.

3)    Absence of white space

Compile error: Expected: end of statement

How to fix: Any identifier that is immediately followed by a &, like name& and affiliation&, is interpreted as a Long variable, so the lack of whitespace in front of the concatenation operator (&) is causing a parse error. To solve the problem, you just need to put a space between the variables and the concatenation operator. Instead of writing name&, write name &.

A Microsoft Access 2010 database is giving me the following error message:

Compile Error: Expected End Of Statement  

Here is the method that is throwing the error message:

Private Sub Form_BeforeUpdate(Cancel As Integer)
    'Provide the user with the option to save/undo
    'changes made to the record in the form
    If MsgBox("Changes have been made to this record." _
        & vbCrLf & vbCrLf & "Do you want to save these changes?" _
        , vbYesNo, "Changes Made...") = vbYes Then
            DoCmd.Save
        Else
            DoCmd.RunCommand acCmdUndo
    End If

    Dim sSQL As String
    sSQL = "SELECT max(Clients.ClientNumber) AS maxClientNumber FROM Clients"
    Dim rs As DAO Recordset
    Set rs = CurrentDb.OpenRecordset(sSQL)
    MsgBox ("Max client number is: " & rs.Fields(1))
End Sub  

The line of code that is throwing the error message is:

 Dim rs As DAO Recordset  

I am not sure if the problem has to do with the syntax of what is on the line preceding it. Can anyone show how to fix this problem? And explain what is going on?

asked Oct 23, 2013 at 1:08

CodeMed's user avatar

You are missing a full stop (period) between the DAO and the Recordset — it should be

Dim rs As DAO.Recordset

Beyond that, you will also have a runtime error on reading the field value, since a DAO Fields collection is indexed from 0, not 1. Hence, change the penultimate line to this:

MsgBox ("Max client number is: " & rs.Fields(0))

Alternatively, reference the field by its name:

MsgBox ("Max client number is: " & rs!maxClientNumber)

answered Oct 23, 2013 at 1:23

Chris Rolliston's user avatar

Chris RollistonChris Rolliston

4,7681 gold badge16 silver badges20 bronze badges

4

You’re mising the semicolon at the end of your Sql statement

answered Oct 24, 2013 at 0:28

Cayucodies's user avatar

 

Nechaevvs

Пользователь

Сообщений: 6
Регистрация: 22.07.2016

Добрый день!
Прошу помочь разобраться с проблемой при заполнении макросом пустой ячейки функцией экселя.
Во вложении мой пример кода, но по нему происходит ошибка Compile error:
Expected: end of statement.
Эта же функция указана во 2ой строке 6ом столбце, необходимо, чтобы она протягивалась вниз до последней заполненной строки 2ого столбца.
Прошу подсказать, как корректно можно подправить данный код.
Буду благодарен за любые подсказки..
По форуму не нашел решение, пытался менять formula на FormulaLocal, но это не помогло

Прикрепленные файлы

  • Help.xlsm (45.6 КБ)

 

Слэн

Пользователь

Сообщений: 5192
Регистрация: 16.01.2013

внутри кавычек кавычки нужно удваивать

 

Nechaevvs

Пользователь

Сообщений: 6
Регистрация: 22.07.2016

Это большой шаг вперед для меня =)
Спасибо.
Теперь значения появляются в ячейке, но не в виде формулы, а в виде текста.. Можете подсказать, каким образом можно преобразовать эту строку в формулу, т.е. добавить «=»? Просто «=»+»формула» выдает ошибку..  

 

Nechaevvs

Пользователь

Сообщений: 6
Регистрация: 22.07.2016

Upd, при указании двойных кавычек внутри кавычек ошибка «Compile error: Expected: end of statement» — ушла.
Но функция в ячейку не вставляется, следующая ошибка:
Run-time error ‘1004’:
Application-defined or object-defined eror.
Новый файл во вложении

Прикрепленные файлы

  • Help.xlsm (45.98 КБ)

 

RAN

Пользователь

Сообщений: 7157
Регистрация: 21.12.2012

Вы пишете «Formula =»
А вставляете «FormulaLocal»
«Formula», она по аглицки пишется.

 

Nechaevvs

Пользователь

Сообщений: 6
Регистрация: 22.07.2016

#6

22.07.2016 18:05:32

Спасибо огромное.
В итоге получается, что изначально была проблема в кавычках, а потом в указании формата формулы.
Все получилось и работает

  • Remove From My Forums
  • Question

  • Hi All,

    I’m trying to adapt my query sql to use in vba & my brain is closing down. I keep getting the compile error: Expected: End of statement. The last time I encountered this message I was able to figure out the quotes but this is a different syntax using
    Dlookup in the sql string.

    Can someone help me past this brain blockage (can’t see the wood for the trees comes to mind)

    Here is the code string

    strSQL = «UPDATE [tblResultsImported] » _
    strSQL = strSQL & «SET tblResultsImported.CouplesInClass = DLookUp(«CountOfClass»,»qryImportClassCount»,»class = ‘» & [class] & «‘»);»

Answers

  • Either remove the  _  continuation from the first row, or make it all one continuation; and remember that each open quote will require a matching close quote. The » before CountOfClass is being read as the closing quote for the one before SET.

    Try

    strSQL = «UPDATE [tblResultsImported] SET tblResultsImported.CouplesInClass = » _
     & «DLookUp(«»CountOfClass»»,»»qryImportClassCount»»,»»class = ‘»» & [class] & «»‘»»);»

    using the fact that you can include a doublequote in a doublequote delimited string by using a doubled doublequote (a fine example of doubletalk!)


    John W. Vinson/MVP

    • Marked as answer by

      Thursday, September 23, 2010 5:08 AM

Return to VBA Code Examples

This tutorial will explain what a VBA Compile Error means and how it occurs.

Before running your code, the VBA Editor compiles the code. This basically means that VBA examines your code to make sure that all the requirements are there to run it correctly – it will check that all the variables are declared (if you use Option Explicit which you should!), check that all the procedures are declared, check the loops and if statements etc. By compiling the code, VBA helps to minimize any runtime errors occurring.

(See our Error Handling Guide for more information about VBA Errors)

Undeclared Variables

If you do not declare variables, but your Option Explicit is switched on at the top of your module, and then you run the macro, a compile error will occur.

VBACompileError VarNotDeclared

If you click OK,  the relevant procedure will go into debug mode.

VBACompileError Debug

Alternatively, before you run your code, you can force a compilation of the code.

In the Menu, select Debug > Compile Project.

VBACompileError Menu

The compiler will find any compile errors and highlight the first one it finds accordingly.

Undeclared Procedures

If you code refers to a procedure that does not exist, you will also get a compile error.

For example:

Sub CallProcedure()
'some code here then 
  Call NextProcedure
End Sub

However, if the procedure – NextProcedure does not exist, then a compile error will occur.

VBACompileError NoProcedure

Incorrect Coding – Expected End of Statement

If you create a loop using For..Each..Next or With..End With and forget to and the Next or the End With… you will also get a compile error.

Sub CompileError()
 Dim wb As Workbook
 Dim ws As Worksheet
 For Each ws In wb
   MsgBox ws.Name
End Sub

VBACompileError NoNext

The same will happen with an If statement if the End If is omitted!

VBACompileError NoEndIf

Missing References

If you are using an Object Library that is not part of Excel, but you are using the objects from the library in your variable declaration, you will also receive a compile error.

VBACompileError MissingRef

This can be solved by either Late Binding – declaring the variables are Objects; or by adding the relevant Object Library to the Project.

In the Menu, select Tools > References and add the relevant object library to your project.

VBACompileError RefBox

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Понравилась статья? Поделить с друзьями:
  • Ошибка comodo security agent could not be started
  • Ошибка community lib симс 4
  • Ошибка communication timeout reset send buffer block
  • Ошибка command line option syntax error type command
  • Ошибка comm error на экскаваторе