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:
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.
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.
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.
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:
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
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
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 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
Nechaevvs Пользователь Сообщений: 6 |
Добрый день! Прикрепленные файлы
|
Слэн Пользователь Сообщений: 5192 |
внутри кавычек кавычки нужно удваивать |
Nechaevvs Пользователь Сообщений: 6 |
Это большой шаг вперед для меня =) |
Nechaevvs Пользователь Сообщений: 6 |
Upd, при указании двойных кавычек внутри кавычек ошибка «Compile error: Expected: end of statement» — ушла. Прикрепленные файлы
|
RAN Пользователь Сообщений: 7157 |
Вы пишете «Formula =» |
Nechaevvs Пользователь Сообщений: 6 |
#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
-
Marked as answer by
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.
If you click OK, the relevant procedure will go into debug mode.
Alternatively, before you run your code, you can force a compilation of the code.
In the Menu, select Debug > Compile Project.
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.
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
The same will happen with an If statement if the End If is omitted!
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.
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.
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!
Learn More!