Ошибка visual basic compile error

При выполнении макросов Excel могут возникнуть ошибки, которые в VBA делят на три категории:

  • Ошибки компиляции
  • Ошибки выполнения
  • Логические ошибки (баги)

Далее мы поговорим о каждом из трёх типов ошибок VBA подробно.

Содержание

  1. Ошибки компиляции
  2. Ошибки выполнения
  3. Перехват ошибок выполнения
  4. Логические ошибки

Ошибки компиляции

Компилятор VBA рассматривает ошибки компиляции как недопустимые и выделяет их в коде ещё до того, как дело дойдёт до запуска макроса.

Если при написании кода допущена синтаксическая ошибка, то редактор VBA сигнализирует об этом немедленно: либо при помощи окна с сообщением, либо выделяя ошибку красным цветом, в зависимости от статуса режима Auto Syntax Check.

Примечание: При включённом режиме Auto Syntax Check каждый раз, при появлении в редакторе Visual Basic во введённом коде синтаксической ошибки, будет показано соответствующее сообщение. Если же этот режим выключен, то редактор VBA продолжит сообщать о синтаксических ошибках, просто выделяя их красным цветом. Опцию Auto Syntax Check можно включить/выключить в меню Tools > Options редактора Visual Basic.

В некоторых случаях ошибка компиляции может быть обнаружена при выполнении компиляции кода, непосредственно перед тем, как макрос будет выполнен. Обычно ошибку компиляции несложно обнаружить и исправить, потому что компилятор VBA даёт информацию о характере и причине ошибки.

Ошибки в Excel VBA

Например, сообщение «Compile error: Variable not defined» при попытке запустить выполнение кода VBA говорит о том, что происходит попытка использовать или обратиться к переменной, которая не была объявлена для текущей области (такая ошибка может возникнуть только если используется Option Explicit).

Ошибки выполнения

Ошибки выполнения возникают в процессе выполнения кода и приводят к остановке выполнения программы. Этот тип ошибок VBA, как правило, также не сложно обнаружить и исправить, так как сообщается информация о характере ошибки и место в коде, где произошла остановка.

Примером такой ошибки может служить попытка выполнить деление на ноль. В результате будет показано сообщение «Run-time error ’11’: Division by zero«.

Ошибки в Excel VBA

В зависимости от структуры проекта VBA, может быть предложено выполнить отладку кода (как показано на рисунке ниже). В этом случае при нажатии на кнопку Debug (в окне сообщения о необходимости отладки) будет выделена цветом строка кода, которая стала причиной ошибки VBA.

Ошибки в Excel VBA

Получив такое сообщение и видя выделенную строку кода, как в приведённом выше примере, обнаружить причину ошибки будет совсем не сложно.

В случае если код сложнее, чем в нашем примере, то, чтобы получить больше информации о причине возникновения ошибки VBA, можно проверить значения используемых переменных. В редакторе VBA для этого достаточно навести указатель мыши на имя переменной, или можно открыть окно отслеживания локальных переменных (в меню редактора View > Locals Window).

Коды различных ошибок выполнения расшифрованы на сайте Microsoft Support (на английском). Наиболее часто встречающиеся ошибки VBA перечислены в этой таблице:

5 Недопустимый вызов процедуры (Invalid procedure call)
7 Недостаточно памяти (Out of memory)
9 Индекс вне заданного диапазона (Subscript out of range)

Эта ошибка возникает при попытке обратиться к элементу массива за пределами заданного размера массива – например, если объявлен массив с индексами от 1 до 10, а мы пытаемся обратиться к элементу этого же массива с индексом 11.

11 Деление на ноль (Division by zero)
13 Несоответствие типа (Type mismatch)

Эта ошибка возникает при попытке присвоить переменной значение не соответствующего типа – например, объявлена переменная i типа Integer, и происходит попытка присвоить ей значение строкового типа.

53 Файл не найден (File not found)

Иногда возникает при попытке открыть не существующий файл.

Перехват ошибок выполнения

Не все ошибки выполнения бывают вызваны недочётами в коде. Например, ошибки VBA не удастся избежать, если для работы макроса необходимо открыть файл с данными, а этого файла не существует. В таких случаях признаком профессионализма будет перехват ошибок и написание кода VBA, который будет выполняться при их возникновении. Таким образом, вместо неприятных сбоев будет происходить изящное завершение работы макроса.

Для того, чтобы помочь справиться с возникающими ошибками, VBA предоставляет разработчику операторы On Error и Resume. Эти операторы отслеживают ошибки и направляют выполнение макроса в специальный раздел кода VBA, в котором происходит обработка ошибки. После выполнения кода обработки ошибки, работа программы может быть продолжена с того места, где возникла ошибка, или макрос может быть остановлен полностью. Далее это показано на примере.

'Процедура Sub присваивает переменным Val1 и Val2 значения,
'хранящиеся в ячейках A1 и B1 рабочей книги Data.xlsx расположенной в каталоге C:Documents and Settings

Sub Set_Values(Val1 As Double, Val2 As Double)

   Dim DataWorkbook As Workbook

   On Error GoTo ErrorHandling

      'Открываем рабочую книгу с данными

      Set DataWorkbook = Workbooks.Open("C:Documents and SettingsData")

      'Присваиваем переменным Val1 и Val2 данные из рабочей книги DataWorkbook

      Val1 = Sheets("Лист1").Cells(1, 1)
      Val2 = Sheets("Лист1").Cells(1, 2)

      DataWorkbook.Close

   Exit Sub

ErrorHandling:

   'Если файл не найден, предлагаем пользователю разместить его в
   'нужном месте и продолжить работу

   MsgBox "Рабочая книга не найдена! " & _
      "Пожалуйста добавьте книгу Data.xlsx в каталог C:Documents and Settings и нажмите OK."

   Resume

End Sub

В этом коде производится попытка открыть файл Excel с именем Data. Если файл не найден, то пользователю будет предложено поместить этот файл в нужную папку. После того, как пользователь сделает это и нажмёт ОК, выполнение кода продолжится, и попытка открыть этот файл повторится. При желании вместо попытки открыть нужный файл, выполнение процедуры Sub может быть прервано в этом месте при помощи команды Exit Sub.

Логические ошибки

Логические ошибки (или баги) возникают в процессе выполнения кода VBA, но позволяют ему выполняться до самого завершения. Правда в результате могут выполняться не те действия, которые ожидалось, и может быть получен неверный результат. Такие ошибки обнаружить и исправить труднее всего, так как компилятор VBA их не распознаёт и не может указать на них так, как это происходит с ошибками компиляции и выполнения.

Например, при создании макроса в процедуре случайно были просуммированы не те переменные, которые требовалось просуммировать. Результат будет ошибочным, но макрос будет продолжать выполняться до завершения.

Редактор Excel VBA предоставляет набор инструментов отладки, которые помогут найти и исправить логические ошибки в коде VBA. В данной статье мы не будем рассматривать подробно эти инструменты. Любознательный пользователь может найти обзор инструментов отладки VBA на сайте Microsoft Help & Support (на английском).

Оцените качество статьи. Нам важно ваше мнение:

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!

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.

In this tutorial, I will show you various ways you can use to handle errors effectively in Excel VBA.

Before we get into VBA error handling, let’s first understand the different types of errors you are likely to encounter when programming in Excel VBA.

Types of VBA Errors in Excel

There are four types of errors in Excel VBA:

  1. Syntax errors
  2. Compilation errors
  3. Runtime errors
  4. Logical Errors

Let’s quickly understand what these errors are and when you’re likely to encounter these.

Syntax Error

A syntax error, as the name suggests, occurs when VBA finds something wrong with the syntax in the code.

For example, if you forget a part of the statement/syntax that is needed, then you will see the compile error.

In the below code, as soon as I hit enter after the second line, I see a compile error. This is because the IF statement needs to have the ‘Then‘ command, which is missing in the below code.

Excel VBA Compile Error - Expected Then or Goto

Note: When you are typing a code in Excel VBA, it checks for each sentence as soon as you hit enter. If VBA finds something missing in the syntax, it instantly shows a message with some text that can help you understand the missing part.

To make sure you see the syntax error whenever there is something missing, you need to make sure Autosyntax check is enabled. To do this, click on ‘Tools’ and then click on ‘Options’. In the options dialog box, make sure that the ‘Auto Syntax Check’ option is enabled.

AutoSyntax Option to be checked

If the ‘Auto Syntax Check’ option is disabled, VBA will still highlight the line with the syntax error in red, but it will not show 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 below code, as soon as I try to run the code, it will show the following error. This happens as I have used the IF Then statement without closing it with the mandatory ‘End If’.

Excel VBA Error - Block If Without End If

A syntax error is also a type of compile error. A syntax error occurs as soon as you hit enter and VBA identifies that something is missing. A compilation error can also occur when VBA doesn’t find anything missing while typing the code, but it does when the code is compiled or executed.

VBA checks each line as you’re typing the code and highlights the syntax error as soon as the line is incorrect and you hit enter. Compile errors, on the other hand, are only identified when the entire code is analyzed by VBA.

Below are some scenarios where you’ll encounter the compile error:

  1. Using an IF Statement without the End IF
  2. Using For statement with the Next
  3. Using Select statement without using the End Select
  4. Not declaring the variable (this works only when Option Explicit is enabled)
  5. Calling a Sub/Function that does not exist (or with wrong parameters)

Note about ‘Option Explicit’: When you add ‘Option Explicit’, you will be required to declare all the variables before running the code. If there is any variable that has not been declared, VBA would show an error. This is a good practice as it shows an error in case you have a misspelled variable. You can read more about Option Explicit here.

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 are being taken care of.

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

Runtime error in Excel VBA

When a runtime error occurs, it will stop the code and show you the error dialog box.

The message in the Run-time error dialog box is a little more helpful. It tries to explain the problem that can help you correct it.

If you click on the Debug button, it will highlight the part of the code that is leading to the error.

Click on Debug to Highlight the code

If you have corrected the error, you can click on the Run button in the toolbar (or press F5) to continue running the code from where it left.

Or you can also click on the End button to come out of the code.

Important: In case you click the End button in the dialog box, it will stop the code at the line at which is encountered. However, all the lines of code before that would have been executed.

Logical Errors

Logical errors would not make your code stop but can lead to wrong results. These could also be the most difficult types of errors to troubleshoot.

These errors are not highlighted by the compiler and need to be manually tackled.

One example of logical error (that I often find myself stuck with) is running into an endless loop.

Another example could be when it gives a result which is wrong. For example, you may end up using a wrong variable in the code or add two variables where one is incorrect.

There are a few ways I use to tackle logical errors:

  1. Insert Message Box at some place in the code and highlight values/data that can help understand if eberything is going as expected.
  2. Instead of running the code at one go, go through each line one by one. To do this, click anywhere in the code and press F8. you would notice that each time you press F8, one line gets executed. This allows you to go through the code one line at a time and identify the logical errors.

Using Debug to Find Compile/Syntax Errors

Once you’re done with the code, it’s a good practice to first compile it before running.

To compile a code, click on the Debug option in the toolbar and click on Compile VBAProject.

Debug Compile VBAProject

When you compile a VBA project, it goes through the code and identifies errors (if any).

In case it finds an error, it will show you a dialog box with the error. It finds errors one by one. So if it finds an error and you have corrected it, you need to run compile again to find other errors (if there are).

When you’re code is free of errors, the Compile VBAProject option will be greyed out.

Note that Compiling will only find ‘Syntax’ errors and ‘Compile’ errors. It will NOT find the run-time errors.

When you’re writing VBA code, you don’t want the errors to crop up. To avoid this, there are many error-handling methods you can use.

In the next few sections of this article, I will be covering the methods you can use for VBA error handling in Excel.

Configure Error Settings (Handled Vs Unhandled Errors)

Before you start working with your code, you need to check for one setting in Excel VBA.

Go to the VBA toolbar and click on Tools and then click on Options.

In the Options dialog box, click on the General tab and make sure that within the ‘Error Trapping’ group, ‘Break on Unhandled Errors’ is checked.

Let me explain the three options:

  1. Break on All Errors: This will stop your code on all types of errors, even when you have used the techniques to handle these errors.
  2. Break in Class Module: This will stop your code on all unhandled errors, and at the same time, if you’re using objects such as Userforms, it will also break within those objects and highlight the exact line causing the error.
  3. Break on Unhandled Errors: This will stop your code only for those errors that are not handled. This is the default setting as it ensures any unhandled errors are brought to your notice. If you’re using objects such as Userforms, this will not highlight the line causing the error in the object, but will only highlight the line that’s referring to that object.

Note: If you work with objects such as Userforms, you can change this setting to ‘Break on Class Modules’. The difference between #2 and #3 is that when you use Break in Class Module, it will take you to the specific line in the object that is causing the error. You can also choose to go with this instead of ‘Break on Unhandled Errors’.

So in a nutshell – if you’re just starting with Excel VBA, ensure ‘Break on Unhandled Errors’ is checked.

VBA Error Handling with ‘On Error’ Statements

When your code encounters an error, there are a few things you can do:

  1. Ignore the error and let the code continue
  2. Have an error handling code in place and run it when an error occurs

Both of these error handling methods ensures that the end user will not get to see an error.

There are a few ‘On Error’ statements that you can use to get these done.

On Error Resume Next

When you use ‘On Error Resume Next’ in your code, any encountered error will be ignored and the code will continue to run.

This error handling method is used quite often, but you need to be cautious when using it. Since it completely ignores any error that may occur, you may not be able to identify the errors that need to be corrected.

For example, if the below code is run, it will return an error.

Sub AssignValues()
x = 20 / 4
y = 30 / 0
End Sub

This happens because you can not divide a number by zero.

But if I use the ‘On Error Resume Next’ statement in this code (as shown below), it will ignore the error and I will not know that there is an issue that needs to be corrected.

Sub AssignValues()
On Error Resume Next
x = 20 / 4
y = 30 / 0
End Sub

On Error Resume Next should be used only when you clearly know the kind of errors your VBA code is expected to throw and it’s alright to ignore it.

For example, below is the VBA event code that would instantly add the date and time value in cell A1 of a newly inserted sheet (this code is added in the worksheet and not in a module).

Private Sub Workbook_NewSheet(ByVal Sh As Object)
Sh.Range("A1") = Format(Now, "dd-mmm-yyyy hh:mm:ss")
End Sub

While this works great in most cases, it would show an error if I add a chart sheet instead of a worksheet. Since a chart sheet does not have cells, the code would throw an error.

So, if I use the ‘On Error Resume Next’ statement in this code, it will work as expected with worksheets and do nothing with chart sheets.

Private Sub Workbook_NewSheet(ByVal Sh As Object)
On Error Resume Next
Sh.Range("A1") = Format(Now, "dd-mmm-yyyy hh:mm:ss")
End Sub

Note: On Error Resume Next Statement is best used when you know what kind of errors you’re likely to encounter. And then if you think it’s safe to ignore these errors, you can use it.

You can take this code to the next level by analyzing if there was an error, and displaying a relevant message for it.

The below code would show a message box that would inform the user that a worksheet has not been inserted.

Private Sub Workbook_NewSheet(ByVal Sh As Object)
On Error Resume Next
Sh.Range("A1") = Format(Now, "dd-mmm-yyyy hh:mm:ss")
If Err.Number <> 0 Then
MsgBox "Looks like you inserted a chart sheet" & vbCrLf & "Error - " & Err.Description
End If
End Sub

‘Err.Number’ is used to get the error number and ‘Err.Description’ is used to get the error description. These will be covered later in this tutorial.

On Error GoTo 0

‘On Error GoTo 0’ will stop the code on the line that causes the error and shows a message box that describes the error.

In simple terms, it enables the default error checking behavior and shows the default error message.

Then why even use it?

Normally, you don’t need to use ‘On Error Goto 0’, but it can be useful when you use it in conjunction with ‘On Error Resume Next’

Let me explain!

The below code would select all the blank cells in the selection.

Sub SelectFormulaCells()
Selection.SpecialCells(xlCellTypeBlanks).Select
End Sub

But it would show an error when there are no blank cells in the selected cells.

So to avoid showing the error, you can use On Error Resume next’

Now, it will also show any error when you run the below code:

Sub SelectFormulaCells()
On Error Resume Next
Selection.SpecialCells(xlCellTypeBlanks).Select
End Sub

So far, so good!

The problem arises when there is a part of the code where error can occur, and since you’re using ‘On Error Resume Next’, the code would simply ignore it and move to the next line.

For example, in the below code, there would no error prompt:

Sub SelectFormulaCells()
On Error Resume Next
Selection.SpecialCells(xlCellTypeBlanks).Select
' .. more code that can contain error
End Sub

In the above code, there are two places where an error can occur. The first place is where we are selecting all blank cells (using Selection.SpecialCells) and the second is in the remaining code.

While the first error is expected, any error after that is not.

This is where On Error Goto 0 comes to rescue.

When you use it, you reset the error setting to default, where it will start showing errors when it encounters it.

For example, in the below code, there would be no error in case there are no blank cells, but there would be an error prompt because of ’10/0′

Sub SelectFormulaCells()
On Error Resume Next
Selection.SpecialCells(xlCellTypeBlanks).Select
On Error GoTo 0
' .. more code that can contain error
End Sub

Error Checking restored with GoTo 0

On Error Goto [Label]

The above two methods – ‘On Error Resume Next’ and ‘On Error Goto 0’ – doesn’t allow us to truly handle the error. One makes the code ignore the error and the second one resume error checking.

On Error Go [Label] is a way with which you can specify what you want to do in case your code has an error.

Below is the code structure that uses this error handler:

Sub Test()

On Error GoTo Label:
X = 10 / 0    'this line causes an error
' ....your remaining code goes here
Exit Sub

Label:
    ' code to handle the error
End Sub

Note that before the Error handling ‘Label’, there is an Exit Sub. This ensures that in case there are no errors, the sub is exited and the ‘Label’ code is not executed. In case you don’t use Exit Sub, it will always execute the ‘Label’ code.

In the example code below, when an error occurs, the code jumps and executes the code in the handler section (and shows a message box).

Sub Errorhandler()
On Error GoTo ErrMsg
X = 12
Y = 20 / 0
Z = 30
Exit Sub
ErrMsg:
MsgBox "There seems to be an error" & vbCrLf & Err.Description
End Sub

Note that when an error occurs, the code has already run and executed the lines before the line causing the error. In the above example, the code sets the value of X as 12, but since the error occurs in the next line, it doesn’t set the values for Y and Z.

Once the code jumps to the error handler code (ErrMsg in this example), it will continue to execute all the lines in and below the error handler code and the exit the sub.

On Error Goto -1

This one is a bit complicated, and in most cases, you’re unlikely to use this.

But I will still cover this as I have faced a situation where this was needed (feel free to ignore and jump to the next section if you’re only looking for basics).

Before I get into the mechanics of it, let me try and explain where can it be useful.

Suppose you have a code where an error is encountered. But all is good as you have one error handler in place. But what happens when there is another error in the error handler code (yeah.. somewhat like the inception movie).

In such a case, you can not use the second handler as the first error has not been cleared. So while you have handled the first error, in VBA’s memory it still exists. And the VBA memory only has a place for one error – not two or more than that.

In this scenario, you can use On Error Goto -1.

It clears the error and frees up VBA memory to handle the next error.

Enough talk!

Let’s me explain now by using examples.

Suppose I have the below code. This will throw an error as there is division by zero.

Sub Errorhandler()
X = 12
Y = 20 / 0
Z = 30
End Sub

So to handle it, I use an error handler code (with the name ErrMsg) as shown below:

Sub Errorhandler()

On Error GoTo ErrMsg

X = 12
Y = 20 / 0
Z = 30
Exit Sub

ErrMsg:
MsgBox "There seems to be an error" & vbCrLf & Err.Description
End Sub

Division by 0 error message

All is good now again. As soon as the error occurs, the error handler is used and shows a message box as shown below.

Now, I expand the code so that I have more code in or after the error handler.

Sub Errorhandler()

On Error GoTo ErrMsg

X = 12
Y = 20 / 0
Z = 30
Exit Sub

ErrMsg:
MsgBox "There seems to be an error" & vbCrLf & Err.Description
A = 10 / 2
B = 35 / 0
End Sub

Since the first error has been handled but the second has not been, I again see an error as shown below.

Second Division by error code

Still all good. The code is behaving in the way we expected it to.

So to handle the second error, I use another error handler (ErrMsg2).

Sub Errorhandler()

On Error GoTo ErrMsg

X = 12
Y = 20 / 0
Z = 30
Exit Sub

ErrMsg:
MsgBox "There seems to be an error" & vbCrLf & Err.Description
On Error GoTo ErrMsg2
A = 10 / 2
B = 35 / 0
Exit Sub

ErrMsg2:
MsgBox "There seems to be an error again" & vbCrLf & Err.Description

End Sub

And this is where it doesn’t work as expected.

If you run the above code, it will still give you a run-time error, even after having the second error handler in place.

This happens as we didn’t clear the first error from VBA’s memory.

Yes, we handled it! But it still remains in the memory.

And when VBA encounters another error, it’s still stuck with the first error, and hence the second error handler is not used. The code stops at the line that caused the error and shows the error prompt.

To clear VBA’s memory and clear the previous error, you need to use the ‘On Error Goto -1’.

So if you add this line in the below code and run it, it will work as expected.

Sub Errorhandler()

On Error GoTo ErrMsg
X = 12
Y = 20 / 0
Z = 30
Exit Sub

ErrMsg:
MsgBox "There seems to be an error" & vbCrLf & Err.Description
On Error GoTo -1
On Error GoTo ErrMsg2
A = 10 / 2
B = 35 / 0
Exit Sub

ErrMsg2:
MsgBox "There seems to be an error again" & vbCrLf & Err.Description

End Sub

Note: The error automatically gets cleared when a subroutine ends. So, ‘On Error Goto -1’ can be useful when you’re getting two or more than two errors in the same subroutine.

The Err Object

Whenever an error occurs with a code, it’s the Err object that is used to get the details about the error (such as the error number or the description).

Err Object Properties

The Err Object has the following properties:

Property Description
Number A number that represents the type of error. When there is no error, this value is 0
Description A short description of the error
Source Project name in which the error has occurred
HelpContext The help context id for the error in the help file
HelpFile A string that represents the folder location and the file name of the help file

While in most cases you don’t need to use Err object, it can sometimes be useful while handling errors in Excel.

For example, suppose you have a dataset as shown below and for each number, in the selection, you want to calculate the square root in the adjacent cell.

Data for Square root in Excel

The below code can do it, but since there is a text string in cell A5, it shows an error as soon as this occurs.

Sub FindSqrRoot()
Dim rng As Range
Set rng = Selection

For Each cell In rng
    cell.Offset(0, 1).Value = Sqr(cell.Value)
Next cell

End Sub

Type Mismatch Error when finding square root

The problem with this type of error message is that it gives you nothing about what has gone wrong and where the issue occurred.

You can use the Err object to make these error messages more meaningful.

For example, if I now use the below VBA code, it will stop the code as soon as the error occurs and show a message box with the cell address of the cell where there is an issue.

Sub FindSqrRoot()
Dim rng As Range
Set rng = Selection

For Each cell In rng
    On Error GoTo ErrHandler
    cell.Offset(0, 1).Value = Sqr(cell.Value)
Next cell

ErrHandler:
MsgBox "Error Number:" & Err.Number & vbCrLf & _
    "Error Description: " & Err.Description & vbCrLf & _
    "Error at: " & cell.Address

End Sub

The above code would give you a lot more information than the simple ‘Type Mismatch’, especially the cell address so that you know where the error occurred.

More description Error when finding the square root

You can further refine this code to make sure your code runs until the end (instead of breaking at each error) and then gives you a list of cell address where the error occurs.

The below code would do this:

Sub FindSqrRoot2()
Dim ErrorCells As String
Dim rng As Range

On Error Resume Next

Set rng = Selection
For Each cell In rng
cell.Offset(0, 1).Value = Sqr(cell.Value)

If Err.Number <> 0 Then
ErrorCells = ErrorCells & vbCrLf & cell.Address
On Error GoTo -1
End If
Next cell
MsgBox "Error in the following cells" & ErrorCells
Exit Sub

End Sub

The above code runs until the end and gives the square root of all the cells that have numbers in it (in the adjacent column). It then shows a message that lists all the cells where there was an error (as shown below):

Shows a message with cell address that have errors

Err Object Methods

While the Err properties are useful to show useful information about the errors, there are two Err methods as well that can help you with error handling.

Method Description
Clear Clears all the property settings of the Err object
Raise Generates a run-time error

Let’s quickly learn what these are and how/why to use these with VBA in Excel.

Err Clear Method

Suppose you have a dataset as shown below and you want to get the square root of all these numbers in the adjacent column.

Data for Square root in Excel - 10 cells

The following code will get the square roots of all the numbers in the adjacent column and show a message that an error occurred for cell A5 and A9 (as these have text in it).

Sub FindSqrRoot2()
Dim ErrorCells As String
Dim rng As Range

On Error Resume Next

Set rng = Selection
For Each cell In rng
cell.Offset(0, 1).Value = Sqr(cell.Value)

If Err.Number <> 0 Then
ErrorCells = ErrorCells & vbCrLf & cell.Address
Err.Clear
End If
Next cell
MsgBox "Error in the following cells" & ErrorCells

End Sub

Note that I have used the Err.Clear method within the If Then statement.

Once an error has occurred and trapped by the If condition, Err.Clear method resets the error number back to 0. This ensures that IF condition only trap the errors for cells where it is raised.

Had I not used the Err.Clear method, once the error occurs, it would always be true in the IF condition, and the error number has not been reset.

Another way of making this work is by using the On Error Goto -1, which resets the error completely.

Note: Err.Clear is different from On Error Goto -1. Err.Clear only clears the error description and the error number. it doesn’t completely reset it. This means that if there is another instance of error in the same code, you won’t be able to handle it before resetting it (which can be done with ‘On Error Goto -1’ and not by ‘Err.Clear’).

Err Raise Method

The Err.Raise method allows you to raise a run-time error.

Below is the syntax of using the Err.Raise method:

Err.Raise [number], [source], [description], [helpfile], [helpcontext]

All these arguments are optional and you can use these to make your error message more meaningful.

But why would you ever want to raise an error yourself?

Good question!

You can use this method when there is an instance of an error (which means that there is going to an error anyway) and then you use this method to tell the user more about the error (instead of the less helpful error message that VBA shows by default).

For example, suppose you have a dataset as shown below and you want all the cells to have numeric values only.

Sub RaiseError()
Dim rng As Range
Set rng = Selection

On Error GoTo ErrHandler

For Each Cell In rng
If Not (IsNumeric(Cell.Value)) Then
Err.Raise vbObjectError + 513, Cell.Address, "Not a number", "Test.html"
End If
Next Cell

ErrHandler:
MsgBox Err.Description & vbCrLf & Err.HelpFile
End Sub

The above code would show an error message that has the specified description and the context file.

Personally, I have never used Err.Raise as I mostly work with Excel only. But for someone who uses VBA to work with Excel along with other applications such as Outlook, Word or PowerPoint, this can be useful.

Here is a detailed article on Err.Raise method in case you want to learn more.

VBA Error Handling Best Practices

No matter how skilled you get a writing VBA code, errors are always going to be a part of it. The best coders are those who have the skills to handle these errors properly.

Here are some best practices you can use when it comes to error handling in Excel VBA.

  1. Use ‘On Error Go [Label]’ at the beginning of the code. This will make sure any error that can happen from there is handled.
  2. Use ‘On Error Resume Next’ ONLY when you’re sure about the errors that can occur. Use it with expected error only. In case you use it with unexpected errors, it will simply ignore it and move forward. You can use ‘On Error Resume Next’ with ‘Err.Raise’ if you want to ignore a certain type of error and catch the rest.
  3. When using error handlers, make sure you’re using Exit Sub before the handlers. This will ensure that the error handler code is executed only when there is an error (else it will always be executed).
  4. Use multiple error handlers to trap different kinds of errors. Having multiple error handler ensures that an error is properly addressed. For example, you would want to handle a ‘type mismatch’ error differently than a ‘Division by 0’ run-time error.

Hope you found this Excel article useful!

Here are some more Excel VBA Tutorials that you may like:

  • Excel VBA Data Types – A Complete Guide
  • Excel VBA Loops – For Next, Do While, Do Until, For Each
  • Excel VBA Events – An Easy (and Complete) Guide
  • Excel Visual Basic Editor – How to Open and Use it in Excel

Learn how to deal with and resolve VBA errors in Excel

Types of Errors in VBA for Excel

Users will often encounter different types of errors in VBA. Below, we offer several strategies for dealing with and resolving them. We will go through techniques you can use to interrogate your code during testing, as well as methods of catching errors at runtime.

Types of Errors in VBA for Excel

Testing and tracking down different types of errors in VBA code can be time-consuming and frustrating. It’s not uncommon to hear programmers say that well over 30% of their time is spent on testing.

Over time, you’ll get better at avoiding errors, but it’s unlikely you’ll ever write perfect code, first-time. By learning how to avoid, deal with, and track down VBA errors, you’ll save yourself a ton of time in the future.

Types of VBA Errors

To make things easier, we’ve categorized the types of coding errors into three groups. For each group, we’ll explore some examples, and then discuss how you might investigate and resolve them.

1. Syntax errors – A specific line of code is not written correctly

2. Compile errors – Issues that happen when putting together lines of code, though the individual lines of code seem to make sense

3. Runtime errors – When the code is usually correct in principle, but an action taken by the user or the data being used leads to unexpected errors.

What are Syntax Errors?

Syntax errors are VBA’s way of telling you if your code makes sense, at the most basic of levels. We can make a simple comparison to the rules of writing a sentence in English:

  • A subject is required.
  • A verb is required.
  • A capital letter is required at the beginning.
  • Punctuation is required at the end.
  • Objects, adjectives, and other grammatical features are optional.

Jane found 18 errors in her VBA code.

In a similar manner, VBA imposes certain rules over what is required in certain situations. For example, when initiating a basic conditional IF statement in your code, you must replicate the following syntax rules for the first line of an IF statement;

  • It must begin with If
  • Next must be a logical test, such as x>10
  • Finally, it must end with the word then

If NumberErrors>20 then

If you break the above rules of English or VBA, your grammar (English) or syntax (VBA)  is considered incorrect.

How to Identify a Syntax Error

The VBA editor highlights syntax errors in red, allowing you to easily identify and resolve them. In addition, if you try to run your code or start a new line, you’ll be presented with the syntax error message below.

Basic syntax error:

Basic syntax erro

Syntax error message box:

Syntax Error Message Box

To make sure the checks occur as you’re typing, enable the “Auto Syntax Check” in the Options menu.

Auto Syntax Check

How to Resolve Syntax Errors

Syntax errors represent mistakes in the way a specific line of your code is written. They must be fixed before you can run your code. With experience, the red text will be all you need to spot the error. But if you’re still stuck, just search online for “if statement syntax vba” or whichever variation suits your needs, and you’ll find plenty of examples of the specific line you’re trying to write.

What are Compile Errors?

Compile errors refer to a wider group of VBA errors, which include syntax errors. Compile errors also identify problems with your code when considered as a whole. The syntax of each individual line may be correct, but when put together, the lines of your code don’t make sense. Compile errors are highlighted when you compile or run your code.

How to Identify a Compile Error

When you run your VBA code, compile errors will be presented in a VBA dialog box as per the examples below.

Alternatively, if your project is long or complex and involves multiple routines, it can be helpful to compile your code before you run it. It prevents situations where half of your code runs successfully and then an error pops up. You can compile your VBA code by clicking Debug Menu →  Compile VBA Project.

Example 1

A compile error for a missing “End if” part of an IF statement. Every individual line in the code is correct, but together, they don’t represent a complete IF statement.

Compile Error - Example 1

Example 2

In this example, the VBA compile process has detected a syntax error, highlighted in red. VBA indicates that the code below is missing a closing bracket on the function.

Compile Error - Example 2

Example 3

Compile errors are common when using Option Explicit and occur when a variable has not been explicitly defined. With Option Explicit activated, a Dim statement is required to declare all variables before they can be used in your code.

Compile Error - Example 3

How to Resolve Compile Errors

VBA compile errors will prevent affected routines from running. Until you fix them, your code cannot be interpreted correctly by VBA. The error message boxes often provide more helpful advice than with syntax errors.

If it’s not immediately obvious to you what the issue is from the error message, try using Microsoft’s Help Center to get an idea of exactly how your statement or function should be written. Here’s an example of the “Block if without end if” error message on the Microsoft website.

Block if without end if" error message on Microsoft page

What are Runtime Errors?

Once you’ve fixed syntax errors and compile errors, you’re ready to start testing or running your code properly to see how well it executes your desired actions or calculations. We call the period of testing, or live execution of code, “runtime.”

Runtime errors cannot be detected by simply looking at the code; they are a result of your code interacting with the specific inputs or data at that time.

Runtime errors are often caused by unexpected data being passed to the VBA code, mismatching data types, dividing by unexpected zeros, and defined cell ranges not being available. Runtime errors are also the most varied and complex to track down and fix.

How to Identify Runtime Errors

The VBA Debug function highlights the problem code in yellow and gives us a small clue as to what is causing the problem.

Example 1

While the code below simply divides one number by the other, there are some instances where it won’t be possible. For example, if cell A1 = 2 and cell A2 = 0, it’s not possible to divide by zero. The runtime error box includes a debug button, which highlights the problem code.

Runtime Error - Example 1

Runtime Errors - Example 1a

Example 2

In this example, I created an array to collect the names of n companies in my worksheet. I then tried to reference the sixth item, which may or may not exist at run time. VBA presents a runtime error message and allows me to press Debug to investigate the issue.

Runtime Error - Example 2

Once I press Debug, VBA highlights the line of code that is causing the problem. Now it’s down to me to use the “Subscript out of range” message to work out what’s going wrong. The subscript out of range error generally means that your code is good in principle, but that the specific item you’re looking for can’t be found. Most commonly, it will happen when referencing cells or ranges in Excel, as well as arrays in your VBA code.

Runtime Error - Example 2a

To make sure the Debug function is enabled, in the Options > General > Error Trapping menu, the default state should be to “Break on Unhandled Errors.” Leave the option checked.

Break on Unhandled Errors

How to Resolve Runtime Errors

Since runtime errors are varied and complex in nature, the solutions are also varied. The two general methods to reduce runtime errors are:

Error Trapping

It’s a good idea to put some thought into what possible scenarios your code might encounter. Even better is testing your code on practice data or with real users. It will allow you to recognize such scenarios in your VBA, with code branching into different outcomes, depending on if errors exist.

Example 1

Here, the ‘On Error Resume Next’ line forces the code to continue, even if an error is detected. We then use the If Err > 0 test to create a warning message, only if the error exists. The ‘On Error Goto 0’ resets VBA to its default state.

Error Trapping - Example 1

Example 2

Here, the code is calculating income per day, based on a monthly income, and a defined number of days. If the number of days is not provided, we skip to a defined point in our code called “NoDaysInMonthProvided:,” where we use the average number of days in a month as a base assumption. While it is simplistic, it shows clearly how to trap an error and skip to a different point in your code.

Error Trapping - Example 2

Clear User Instructions

Clear documentation and worksheet labels will ensure that your users interact with your model in the way that you intended. It will help prevent them when inputting text, instead of numbers, or leaving zeros that may later impact your code.

Summary

There are three key types of errors in VBA that can affect your code in different ways. It’s important to activate VBA’s error-detecting options, such as the debugger and auto syntax checking. They will help you to establish the location and nature of the errors.

More Resources

CFI is the official provider of the global Commercial Banking & Credit Analyst (CBCA)™ certification program, designed to help anyone become a world-class financial analyst. To keep advancing your career, the additional resources below will be useful:

  • #REF Excel Errors
  • Excel VBA Examples
  • Tips for Writing VBA in Excel
  • VBA Methods
  • See all Excel resources

A bug is a mistake or error in a program that causes it not to work correctly. Debugging is the process of removing and fixing bugs to get a program to function properly. There are different types of bugs that have different causes and solutions. Bugs can be errors, mistakes, oversights, or poorly implemented logic. Some bugs are easy to detect and fix while others are difficult to recognize and rectify. A bug will ultimately cause a compile error, a runtime error, or an incorrect result.

Compile Errors

Compile Errors occur at compile-time when a language rule has been broken. A program will not run if it has an error in compilation. To detect compile errors use Debug → Compile VBAProject on the toolbar in the Visual Basic Editor. Using Debug → Compile will compile the code in all modules and raise an error message if there is a compile error anywhere, whereas running a procedure in one module may not show the compile error in another procedure or module.

Compile Error Procedures
Debug Compile
Compile Error Procedures Debug Compile

Syntax Errors are compile errors that occur because a syntax rule has been broken. Syntax is the structure of a language and determines what is considered a valid statement. By default, Auto Syntax Check is enabled and the Visual Basic Editor will alert syntax errors and certain other compile errors and highlight them red. If auto syntax check is disabled, pop-up messages will not appear but syntax errors will still appear in red. To enable or disable auto syntax check go to Tools → Options → Editor → Code Settings → Auto syntax check.

Disable Auto Syntax Check

Unhandled Runtime Errors

Runtime Errors occur while a program is running. Unhandled runtime errors will cause program execution to pause and a message will be displayed. The user can either press End to end execution of the program or press Debug to open the Visual Basic Editor and view the line of code that caused the runtime error. Runtime errors can be handled using the On Error statement which is discussed in the Error Handling section.

Runtime Error

Logical Errors

Bugs which cause incorrect output can be the trickiest to debug because the code can appear to work properly under the right conditions but then work incorrectly under other conditions. These silent logical errors are usually caused by poorly thought-out or poorly implemented logic or overlooking aspects of a problem or solution. This type of bug can often be caught through testing and reviewing the output of the code.

Public Function RandomLong(MinValue As Long, MaxValue As Long) As Long

    'BAD CODE - If MinValue > MaxValue erroneous results occur

    Randomize
    RandomLong = Int((MaxValue - MinValue + 1) * Rnd + MinValue)

End Function

Public Function RandomLong(MinValue As Long, MaxValue As Long) As Long

    'FIXED - Unacceptable state causes a runtime error instead of returning wrong answers

    If MinValue > MaxValue Then
        Err.Raise 5
    End If

    Randomize
    RandomLong = Int((MaxValue - MinValue + 1) * Rnd + MinValue)

End Function

A runtime error could exist within a silent error if it only occurs under specific conditions. Code may run normally under normal conditions but then break when an edge case is encountered, causing an unhandled runtime error which can leave a program or associated data in an intermediate state.

Debug Object

The Debug object contains two methods which assist in debugging VBA code, Print and Assert. The Debug object has a default global instance and cannot be instantiated. The Debug object can be accessed at any time in VBA just by typing Debug.

Debug.Print

Debug.Print is used to print text to the Immediate Window.

Public Sub Example()

    Debug.Print "Hello, World!"

End Sub

Debug Print

Debug.Assert

Debug.Assert will pause execution if a boolean expression does not evaluate to True. If the expression evaluates to False or Null execution will be paused.

Public Sub Example()

    Debug.Assert 1 > 0
    Debug.Assert True
    Debug.Assert 1

    Debug.Assert 1 < 0  'Pauses Execution
    Debug.Assert False  'Pauses Execution
    Debug.Assert 0      'Pauses Execution
    Debug.Assert Null   'Pauses Execution

End Sub

Debug Assert

Pause Program Execution

There are a number of ways to cause a program to pause execution and allow the user to inspect the state of a program in break mode.

Breakpoints

Breakpoints can be used in the Visual Basic Editor to pause program execution when a particular line of code is reached. Execution will pause before the line of code is executed. Breakpoints can be toggled by clicking in the margin next to the line of code, right-clicking the line of code and selecting Toggle → Breakpoint, or by using the Edit or Debug toolbars.

Breakpoint

Breakpoint Paused

Stop Statement

The Stop statement will pause execution when the keyword is encountered in the code.

Stop Statement

Watches

Watches can be used to pause execution when an expression evaluates to True or when the value of an expression changes.

Watch Break When Value Is True
Watch Break When Value Is True Paused

Runtime Errors

By default, when an unhandled runtime error is encountered a message will appear describing the error, giving the option to End program execution or to Debug. Selecting Debug will jump to the line of code that caused the error and leave program execution paused.

Unhandled Runtime Error

Different error trapping options can be selected to pause execution on all errors or to pause on errors inside class modules.

Error Trapping Option Description
Break on All Errors Will enter break mode when any error is encountered regardless of error handling code.
Break in Class Module Will enter break mode and show error inside class modules.
Break on Unhandled Errors This is the default setting. Will enter break mode when an unhandled runtime error occurs.

Error Trapping Options

Debug.Assert

Debug.Assert will cause execution to pause if a boolean expression does not evaluate to True. If the expression evaluates to False or Null execution will pause.

Public Sub Example()

    Debug.Assert 1 = 0
    Debug.Assert False
    Debug.Assert 0
    Debug.Assert Null

End Sub

Stepping Through Code

There are tools in the Visual Basic Editor for stepping through code which allow developers to take a close look at the way a program executes each line of code. There is: Step Into, Step Over, Step Out, and Run To Cursor. These tools can be accessed from the Debug Toolbar or by using keyboard shortcuts.

Tool Shortcut Description
Step Into F8 Executes a line of code and enters into procedures.
Step Over Shift + F8 Executes a line of code but will not enter procedures.
Step Out Ctrl + Shift + F8 Executes all lines of code within a procedure.
Run to Cursor Ctrl + F8 Executes all lines of code up to where the cursor is currently located.

Navigating Code

Navigating code is an important skill for programming as well as debugging. When a project grows it becomes more complicated to navigate the code. The Visual Basic Editor provides tools that facilitate navigating code.

Definition Shortcut

The Definition shortcut allows the developer to jump directly to a where a variable or procedure is defined. To jump to the definition of a variable or procedure right-click on the identifier and select Definition from the right-click menu or use the keyboard shortcut Shift + F2.

Definition

LastPosition Shortcut

The LastPosition shortcut allows the developer to jump to the position in code they last edited. To jump to the last position right-click in the Visual Basic Editor and select LastPosition or use the keyboard shortcut Ctrl + Shift + F2.

Last Position

Bookmarks

Bookmarks can be used to explicitly set positions in the code that can be cycled through. To set a Bookmark right-click on the line of code and select Toggle → Bookmark. To cycle through Bookmarks, use the Edit Toolbar.

Toggle Bookmark

Object Box and Procedure Box

The object box and procedure box drop-downs allow a developer to view all the objects and procedures in a module and jump directly to specific procedures as well as insert event procedures if applicable. The object box and procedure box are located at the top of the coding window. The object box is on the left and the procedure box is on the right.

Procedure Box

Split Code Window

The code window can be split so different parts of the same code window can be viewed simultaneously. To split the code window drag the handle at the top right corner of the code window.

Split Handle

Split code windows view the same code and changes in either window are reflected in both windows.

Split

Module And Procedure View

Code windows can be toggled between module view and procedure view. Module view makes the entire module visible in the code window. Procedure view makes only the current procedure visible in the code window. To toggle between module view and procedure view use the toggle buttons at the bottom left corner of the code window.

Module Procedure View

Useful Shortcuts

Action Shortcut Description
Intellisense Ctrl + j Shows options for completing code
Auto-Completion Ctrl + space Completes code or shows options for completing code
Definition Shift + F2 Jumps to where a variable or procedure is defined
Last Position Ctrl + Shift + F2 Jumps to the last active position in a code module

Important Windows

The Immediate Window, Locals Window, and Watch Window are all powerful debugging tools. These windows can be accessed from the View menu in the Visual Basic Editor.

VBE View Menu

Immediate Window

The Immediate Window can be used to view output, run code, and evaluate expressions. The Immediate Window can be accessed by pressing Ctrl + g in the Visual Basic Editor or from View → Immediate Window.

Immediate Window Examples

Debug.Print

Debug.Print outputs text to the immediate window. For example, Debug.Print «Hello, World!» will output «Hello, World!» to the immediate window.

Call Procedures

Procedures can be called from the immediate window by typing the name of the procedure followed by any parameters and pressing enter.

Evaluate Expressions Using «?»

To evaluate an expression in the immediate window type a «?» followed by the expression and press enter.

Execute Code Statements

Code can be typed directly in the immediate window and executed. Because only one line can be used in the immediate window to type code, write multiple statement using the «:» statement separator.

Locals Window

The Locals windows is used to track the values and types of variables during program execution. Pausing execution, stepping through code, and looking at the locals window is an effective way to observe changes in the state of a program. The Locals Window can be accessed from View → Locals Window.

Locals Window

Watches

The Watch Window is used to view how expressions evaluate during a program’s execution and to pause execution when certain conditions are reached. To Add a watch, highlight an expression, right-click the expression, and select Add Watch. Alternatively, right-click the Watch Window, select Add Watch, and type the expression. To access the Watch Window navigate to View → Watch Window.

Right-Click Add Watch
Add Watch
Watch Break on Value Change

Call Stack Window

The call stack window shows a list of active procedures. To see the call stack dialog either navigate to View → Call Stack, click the call stack icon on the Debug toolbar, or use the shortcut Ctrl + L.

Call Stack Window

Понравилась статья? Поделить с друзьями:
  • Ошибка vmware authorization service is not running
  • Ошибка visio непредвиденный конец файла
  • Ошибка video drivers в days gone
  • Ошибка vis на скании что означает
  • Ошибка video driver is out of memory