Excel vba expected end of statement

 

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

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

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

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

 

Nechaevvs

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

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

#6

22.07.2016 18:05:32

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

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 &.

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!

  • Remove From My Forums
  • Вопрос

  • Hi All

    I am trying to adopt the Code(1)….

    Code(1)

    http://www.excelforum.com/excel-programming-vba-macros/637999-vba-for-olap-pivot-table.html

    Dim EmployeeCell As Range
    Dim strPageItem As String
    Dim strOLAPMemberName As String
    strOLAPMemberName = "[Matter Resp Partner].[Managed Ptr Name]"  'pivotfield string
        
    For Each EmployeeCell In [Employee_numbers]
        strPageItem = "[Matter Resp Partner].[Managed Ptr Name].[" & EmployeeCell.Value & "]"   'string concatenation
        Debug.Print strPageItem
            
        ActiveSheet.PivotTables("PivotTable1").PivotFields(strOLAPMemberName).AddPageItem (strPageItem, True)
    Next EmployeeCell


    …to my needs and wrote code(2). It gives me two errors:

    code(2)

    Sub New_macro()
    
    Dim Spread As Range
    Dim strPageItem As String
    Dim SpreadName As String
    Dim SpreadRange As Range
    
    SpreadName = "[Biblia - data].[Spread Mapping & Market]"
    SpreadRange = Worksheets("Spread").Range(C2, C2).End(xlUp).Row
    
    For Each Spread In [SpreadRange]
        strPageItem = "[Biblia - data].[Spread Mapping & Market].&["&Spread.Value&"]"  'ERROR: EXPECTED END OF STATEMENT  "]"
        Debug.Print strPageItem
        
        ActiveSheet.PivotTables("PivotTable1").PivotFields(SpreadName).AddPageItem(strPageItem, True) 'ERROR: EXPECTED: =
    Next Spread
    
    End Sub

    What’s wrong with this? How the code(2) should look like?

    I am using excel 2013

    • Изменено

      4 октября 2015 г. 20:13

Ответы

  • Try:

    For Each Spread In [SpreadRange] strPageItem = "[Biblia - data].[Spread Mapping & Market].[" & Spread.Value & "]" 'ERROR: EXPECTED END OF STATEMENT "]" Debug.Print strPageItem ActiveSheet.PivotTables("PivotTable1").PivotFields(SpreadName).AddPageItem strPageItem, True 'ERROR: EXPECTED: = Next Spread

    When building a string, separate any name from an & with a space.

    When coding a method that doesn't use a returned value, separate the method (.AddPageItem) from
    the first parameter with a space, not a (


    Rod Gill
    Author of the one and only Project VBA Book

    www.project-systems.co.nz

    • Помечено в качестве ответа
      Bartek Wachocki
      5 октября 2015 г. 11:56

Fluff

Fluff

MrExcel MVP, Moderator


  • #2

It looks like you’re missing some spaces, try

Code:

    URL = "https://www.google.co.uk/maps/dir/" & Cells(r, 12).Value & "/" & Cells(r2, 12).Value

SR1

Board Regular


  • #3

The spaces are missing because Excel won’t accept that line of code, otherwise they would be inserted automatically.

The code still doesn’t work if I insert the spaces myself.

Fluff

Fluff

MrExcel MVP, Moderator


  • #4

otherwise they would be inserted automatically.

I wouldn’t count on that. Spaces aren’t always added automatically.
When I placed your code in a module, that line was highlighted red, once the spaces were added, the text became black & the compiler showed no further errors.
As I have no idea what your textbox values are, or what your data looks like, there’s not much more I can do to help.
Can you upload your file to dropbox, or similar & post a link here?

  • #5

Similar to @Fluff‘s comments, adjusting for the spaces prevents the line being highlighted in red. Checking your code again, I can’t see anything inherently wrong aside from those spaces:

Code:

Private Sub CommandButton2_Click()

    Dim x       As Long
    Dim y       As Long
    Dim LR      As Long
    Dim strURL  As String
    
    Const GOOGLE_MAPS   As String = "https://www.google.co.uk/maps/"
    
    Application.ScreenUpdating = False
    
    TextBox2.Value = ""
    
    On Error GoTo InvalidAddress:
            
    LR = Cells(Rows.count, 13).End(xlUp).row
    x = Cells(1, 13).Resize(LR).find(what:=TextBox1.Value, LookIn:=xlFormulas, lookat:=xlPart).row
    
    If Len(TextBox2.Value) = 0 Then
        strURL = GOOGLE_MAPS & "place/" & Cells(x, 12).Value
    Else
        y = Cells(1, 13).Resize(LR).find(what:=TextBox2.Value, LookIn:=xlFormulas, lookat:=xlPart).row
        strURL = GOOGLE_MAPS & "dir/" & Cells(x, 12).Value & "/" & Cells(y, 12).Value
    End If
    
    Application.ScreenUpdating = True
    ActiveWorkbook.followhyyperlink Address:=strURL, NewWindow:=True
    Exit Sub
    
InvalidAddress:
    With Application
        .Goto Cells(1, 1), True
        .ScreenUpdating = True
    End With
    MsgBox Replace("We cannot find this address.@1@1Please check your input", "@1", vbCrLf), vbExclamation, "Input Error"


End Sub

Last edited: Sep 18, 2017

Fluff

Fluff

MrExcel MVP, Moderator


  • #6

@JackDanIce
One minor typo, you’ve an extra y in hyperlink, should be

Code:

ActiveWorkbook.FollowHyperlink Address:=strURL, NewWindow:=True

SR1

Board Regular


  • #7

Thanks, the line in my original code is now accepted with all the right spaces inserted. Must have been the «&» immediately following «Value» that threw it, but it’s strange, I’ve never encountered that problem before.

And thanks Jack for taking the trouble to decipher and reconstruct my code, I’ll try that if mine still doesn’t work!

Last edited: Sep 18, 2017

  • #8

@Fluff Thanks mate, good spot!

Last edited: Sep 18, 2017

  • #9

Thanks, the line in my original code is now accepted with all the right spaces inserted. Must have been the «&» immediately following «Value» that threw it, but it’s strange, I’ve never encountered that problem before.

You always need to provide a space between a variable name and the ampersand (&) following it for a line of code involving concatenation. The reason has to do with VB being backward compatible, syntax-wise, with older VB’s and even the DOS versions of BASIC that preceded it. In the «old days» (and in today’s VBA if you want), you could specify a variable’s data type by using suffix characters attached to the end of the variable’s name. The ampersand character happens to be one of those suffix characters. Placing an ampersand at the end of a variable’s name makes the variable a Long data type… the others being percent sign (%) for Integer, exclamation mark (!) for Single, pound sign (#) for Double, dollar sign ($) for String and, although the data type is «newer», the at sign (@) for Currency. Anyway, VB’s problem comes from its considering the second ampersand in this string (no space between it and the variable name in front of it)…

Code:

UserName = "Rick"
MsgBox "Thank You "&UserName&" for taking part in this survey"

to be the Long data type suffix character meaning there is no concatenation symbol for the variable and the text following it. I know, it should be able to figure out that UserName contains a String value so that it can’t be a Long, but it can’t. Anyway, you can see this in action by putting in the ampersand that VB is missing.

Code:

UserName = "Rick"
MsgBox "Thank You "&UserName&&" for taking part in this survey"

The above string of text will not raise an error when the above MsgBox statement is typed in; instead, the automatic spacing that VB does will take place around the second ampersand once the statement is committed. Now, of course, you will get a type-declaration error when you attempt to actually run this code because UserName is (presumably) Dim’med as a String and the concatenation of a declared Long variable and a String is improper.

Anyway, that is the ‘why’ of the error you mentioned.

Fluff

Fluff

MrExcel MVP, Moderator


  • #10

@Fluff Thanks mate, good spot!

Happened to notice that it hadn’t been capitalised, so had a better look.
@Rick Rothstein
Thanks for the explanation. I’ve always known that the spacings aren’t always inserted, but never understood why.

Last edited: Sep 18, 2017

Like this post? Please share to your friends:
  • Excel vba exit with
  • Excel vba exit function
  • Excel vba excel version
  • Excel vba count not
  • Excel vba copy sheet to new sheet