Меню

Division by zero vba ошибка

Permalink

Cannot retrieve contributors at this time

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Division by zero (Error 11)

vblr6.chm1011128

vblr6.chm1011128

office

3c6783d9-24a4-ef25-fdab-9e26a08e35a9

06/08/2017

medium

Division by zero isn’t possible. This error has the following cause and solution:

  • The value of an expression being used as a divisor is zero.

    Check the spelling of variables in the expression. A misspelled variable name can implicitly create a numeric variable that is initialized to zero. Check previous operations on variables in the expression, especially those passed into the procedure as arguments from other procedures.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

[!includeSupport and feedback]

Permalink

Cannot retrieve contributors at this time

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Division by zero (Error 11)

vblr6.chm1011128

vblr6.chm1011128

office

3c6783d9-24a4-ef25-fdab-9e26a08e35a9

06/08/2017

medium

Division by zero isn’t possible. This error has the following cause and solution:

  • The value of an expression being used as a divisor is zero.

    Check the spelling of variables in the expression. A misspelled variable name can implicitly create a numeric variable that is initialized to zero. Check previous operations on variables in the expression, especially those passed into the procedure as arguments from other procedures.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

[!includeSupport and feedback]

Replace all of your code: —

private sub textbox1_change()
if textbox1.value = "" then exit sub 
if textbox2.value = "" then exit sub 
textbox3.value = cdbl(textbox1.value) / cdbl(textbox2.value)
end sub 
private sub textbox2_change()
if textbox1.value = "" then exit sub
if textbox2.value = "" then exit sub
textbox3.value = cdbl(textbox1.value) / cdbl(textbox2.value)
end sub 

With this code: —

Private Sub textbox1_change()
ShowResult
End Sub
Private Sub textbox2_change()
ShowResult
End Sub
Private Sub ShowResult()
Dim Str1        As String
Dim Str2        As String
Str1 = Trim(textbox1.Value)
Str2 = Trim(textbox2.Value)
If (Str1 = "") Or (Str2 = "") Then Exit Sub
If (IsDouble(Str1) = False) Or (IsDouble(Str2) = False) Then
    textbox3.Value = "NA"
Else
    If (CDbl(Str2) = 0) Or ((CDbl(Str2) + CDbl(Str1)) = 0) Then
        textbox3.Value = "NA"
    Else
        textbox3.Value = CDbl(Str1) / CDbl(Str2)
    End If
End If
End Sub
Private Function IsDouble(ByVal StrValue As String) As Boolean
Dim DblTest As Double
On Error GoTo ErrorHandle
DblTest = CDbl(StrValue)
IsDouble = True
Exit Function
ErrorHandle:
Err.Clear
End Function

This will check for values that can’t be Double data types (i.e. a string) and bad division (i.e. error code 6 and 11).

EDIT: —
The below is walkthrough of what is happening in the above code.

The procedures textbox1_change and textbox2_change are doing the same thing so to avoid repetition of code; they both call on the one instance of that code.

Private Sub textbox1_change()
ShowResult
End Sub

Private Sub textbox2_change()
ShowResult
End Sub

After that, there is the new procedure ShowResult that holds the single instance of the code that textbox1_change and textbox2_change call upon.

Private Sub ShowResult()
Dim Str1        As String
Dim Str2        As String
Str1 = Trim(textbox1.Value)
Str2 = Trim(textbox2.Value)
If (Str1 = "") Or (Str2 = "") Then Exit Sub
If (IsDouble(Str1) = False) Or (IsDouble(Str2) = False) Then
    textbox3.Value = "NA"
Else
    If (CDbl(Str2) = 0) Or ((CDbl(Str2) + CDbl(Str1)) = 0) Then
        textbox3.Value = "NA"
    Else
        textbox3.Value = CDbl(Str1) / CDbl(Str2)
    End If
End If
End Sub

The ShowResult code does a number of checks.

First it places textbox1 into Str1 and textbox2 into Str2 and using trim on them. Trim means that leading and trailing spaces are removed. For example if the textbox1 value was » » (maybe done by copy and paste by the user) then technically it’s not empty and could cause an error.

Dim Str1        As String
Dim Str2        As String
Str1 = Trim(textbox1.Value)
Str2 = Trim(textbox2.Value)

The next check is if either value is empty then exit the procedure, much like you did before but now on a single line.

If (Str1 = "") Or (Str2 = "") Then Exit Sub

The next check calls another procedure that does a check to ensure the value could be converted to a double. for Example CDbl("Hello World!") would fail because it’s not a number to begin with. So this check gets around that potential issue, if its not a number that can be divided then output ‘NA’.

If (IsDouble(Str1) = False) Or (IsDouble(Str2) = False) Then
    textbox3.Value = "NA"

The final check is that if the second value is zero or both are zero then «NA2 is output, else the division is done and output.

If (CDbl(Str2) = 0) Or ((CDbl(Str2) + CDbl(Str1)) = 0) Then
    textbox3.Value = "NA"
Else
    textbox3.Value = CDbl(Str1) / CDbl(Str2)
End If

This is the final procedure that was called by ShowResult to check the value could be converted to a Double data type. It tried to do the conversion, if an error occurs the error is cleared and false (by default) will be returned to the caller, if there is no error then true is output.

Private Function IsDouble(ByVal StrValue As String) As Boolean
Dim DblTest As Double
On Error GoTo ErrorHandle
DblTest = CDbl(StrValue)
IsDouble = True
Exit Function
ErrorHandle:
Err.Clear
End Function

Hope this helps.

При выполнении макросов 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 (на английском).

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

irinka-1986

1

16.03.2011, 10:23. Показов 14532. Ответов 1

Метки нет (Все метки)


Помогите может чего напутала!!! Раньше работало, а теперь выдает ошибку «run-time error 11 division bu zero»

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Public Sub Задача_3()
Dim A As Single, B As Single, M As Integer, H As Single, X As Single, F As Single, S As String
A = InputBox("Ведите начало отрезка a", "Задача 3 Иринка")
B = InputBox("Введите конец отрезка b", "Задача 3 Иринка")
M = InputBox("Введите число точек m", "Задача 3 Иринка")
H = (B - A) / M
Worksheets(1).Cells(1, 1).Value = "X"
Worksheets(1).Cells(1, 2).Value = "F"
i = 2
For X = A To B Step H
F = (Pi / 2) - (Atn(X / (Sqr(1 - (X ^ 2)))))
X = Format(X, "00.000")
F = Format(F, "00.000")
Worksheets(1).Cells(i, 1).Value = X
Worksheets(1).Cells(i, 2).Value = F
i = i + 1
Next X
i = i + 1
Worksheets(1).Cells(i, 1).Value = "Программу выполнила Иринка"
S = Now
i = i + 1
Worksheets(1).Cells(i, 1).Value = S
End Sub
 
При a = 0.5
b=1
m = 5

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

Grigoriy251

39 / 27 / 1

Регистрация: 11.01.2011

Сообщений: 113

16.03.2011, 14:33

2

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Public Sub Задача_3()
Dim A As Single, B As Single, M As Integer, H As Single, X As Single, F As Single, S As String
A = InputBox("Ведите начало отрезка a", "Задача 3 Иринка")
B = InputBox("Введите конец отрезка b", "Задача 3 Иринка")
M = InputBox("Введите число точек m", "Задача 3 Иринка")
H = (B - A) / M
Worksheets(1).Cells(1, 1).Value = "X"
Worksheets(1).Cells(1, 2).Value = "F"
i = 2
For X = A To B Step H
If X <> 1 Then F = (Pi / 2) - (Atn(X / (Sqr(1 - (X ^ 2))))) ' 
X = Format(X, "00.000")
F = Format(F, "00.000")
Worksheets(1).Cells(i, 1).Value = X
Worksheets(1).Cells(i, 2).Value = F
i = i + 1
Next X
i = i + 1
Worksheets(1).Cells(i, 1).Value = "Программу выполнила Иринка"
S = Now
i = i + 1
Worksheets(1).Cells(i, 1).Value = S
End Sub

(Atn(X / ( Sqr(1 — (X ^ 2)))))
У тебя получается Sqr(1 — (1 ^ 2)) =0
когда X=1
А дальше идет деление на ноль

При a = 0.5
b=1
m = 5



0



Just like any other programming language, VBA has no luck when it comes to errors and you have to deal with them, no matter what. They may come from different sources, like bad coding, impossible operations (like zero division), or unexpected errors.

The best way to deal with it is to have a proper understanding of all the possible outcomes of the result that you could get with code. Look at the below example where we have a VBA code that calculates the square root of the number using the value which you have in the selected cell.

Sub Square_Root()
ActiveCell.Value = ActiveCell.Value ^ (1 / 2)
End Sub

But if the active cell has a value other than a number, you’ll get a run-time error, just like below.

Error Settings in VBA (Error Trapping)

In the VBA option, you can configure the setting to deal with errors before you start writing codes. To open the VBA settings, go to Tools ➤ Options ➤ Generals ➤ Error Trapping. Here you have three options which you can use.

  • Break on All Errors: If you have this option activated, VBA will stop the code for all types of errors even if you have used all kinds of error handling techniques.
  • Break-in Class Module: With this option, VBA will stop all your codes that are not handled by any technique. And if you’re using objects such as Userforms, it will also break within those objects and highlight the exact line where the error is.
  • Break on Unhandled Errors: This is the default setting that helps you to know about all the errors where you are not using any error handling technique and stop the code for all the unhandled errors. (But, 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).

Types of VBA Errors

To understand VBA errors, you can split them into four categories, and below is the explanation of these types of errors.

1. Syntax Errors

While writing VBA code you need to follow a particular Syntax and when you skip it or don’t write it in the way it should be you can face SYNTAX error (also called Language error). It’s like typos that you do while writing your codes.

Well, VBA helps you by pointing out these errors by showing an error message. You just need to make sure you have “Auto Syntax Check” activated in your VB editor.

Go to the Tool ➤ Options and make sure to tick the “Auto Syntax Check”. With this, whenever you make a SYNTAX error, VBA will show an error message.

But if “Auto Syntax Check” is disabled VBA still highlights the line of code with the error but won’t show the error message.

2. Compile Errors

It comes when you write code to perform an activity, but that activity is not valid or can’t be performed by VBA. The best example is where you have a code using the IF statement but missed to add END IF at the end of the statement and now when you run this VBA will show you a compilation error message.

Apart from this, there are some other examples of compile errors:

  • Using For without Next (For Next).
  • Select without End Select (Select Case).
  • Not Declaring a Variable when you have “Option Explicit” enabled.
  • Calling a Sub/Function that does not exist.

3. Runtime Errors

A runtime error occurs at the time of executing the code. Remember the example, I shared with you above when the code calculated the square root of a number.

When a runtime error occurs while running code, it stops the code and shows you the error dialog box and that error box talks about the nature of the error you have. Let’s say you have written a code that opens a workbook from the location which you have specified but now that workbook is relocated or deleted by someone.

So, when you run the code, VBA will show you a runtime error as it can’t find that file on that location. The message you get in a run time error describes the reason which helps you to understand the reason for the error.

And when a runtime error occurs it stops the execution of the code. If you click on the “Debug” button it shows you the line of code that has that error by highlighting it yellow. Or you can click on the “End” button to stop the code to execute and close the error message.

4. Logical Error

It’s not an error but a mistake while writing code. These types of errors sometimes can give you nuts while finding them and correcting them.

Let’s say you write code and while declaring a variable you used the wrong data type, or you have used the wrong calculation steps. In this case, your code will work fine, and you won’t find this error easily. The best way to deal with this kind of problem is to run each line of code one by one.

Using Debug Tools in VBA

VBA provides you a set of tools to debug your code and remove bugs from your codes.

1. Compile VBA Project

In Visual Basic Editor, there’s an option that you can use instantly after completing your code. These compile options scan each line of your code and show a message box if there is an error in your code.

Note: Compile VBA option only traces Syntax and Compile errors, not runtime errors as these errors only rise when a code is running. To use Compile VBA Project, go to ➤ Debug ➤ Compile VBA Project.

Once you run “Compile VBA Project” and you have no error in your code, the options will be greyed out.

2. Run Each Line of Code One by One

This is how I do it. When I complete a code, I simply run it line by line to check if there’s an error occurring. It may take time, but it helps you to get to about all the errors (Syntax, Compile, and Run-Time).

On the “Debug Toolbar”, there’s a button “Step In” which you can use to execute a code line by line or you can simply press F8 to execute a single line and then press it again to execute the next line in the code.

Using “On ERROR” Statement to Handle VBA Errors

It’s important to check your codes and find possible errors in all the debugging ways you have. But, the best and most effective way is to create error-handling statements that can deal with an error and make your code flawless while executing. Let’s learn about these statements. When an error occurs in a VBA code the best possible ways to handle that error can be:

  • Let the VBA ignore the error and execute the code
  • Let a special set of statements to run when an error occurs.

In both solutions, you can use “On Error” statements. Below four “On Error” statements that you can use. And now, let’s look at each statement one by one.

1. On Error Resume Next

This simple line of code lets VBA continue executing the code despite the occurrence of an error. The IDEA is simple: Move to the next line of the code if there’s an error found somewhere while executing.

In the below code, you have two lines of code:

  • The first line says the value  of cell A1 is 25 divided by 0
  • And the second line says the value cell A2 is 10 divided by 5

Now there’s a problem with the code which you have inline one. As you know if you divide anything with 0 the result will be an error.  So, when you run this code VBA will show an error message “Run-time error ‘11’ Division by Zero” and stop the execution.

But when you add the “On Error Resume Next” at the very beginning of the code and run the code, VBA simply skips that line of code where the error occurs and continues with the second line and add that value in cell A2.

Sub myDivide()
On Error Resume Next
    Range("A1").Value = 25 / 0
    Range("A2").Value = 10 / 5
End Sub

So, whenever you want your code to get executed despite an error occurring anywhere simply use the “On Error Resume Next” statement in your code.

But here’s one more thing you need to note down: It will only skip errors that occur after it.

Let’s say if an error occurs at line 5 and you have added “On Error Resume Next” on line 8 then it would not skip that error.  So, the best way is to add it as the first line of the code in the procedure.

2. On Error GoTo 0

It’s the default behavior of VBA that when an error occurred it stops the execution of the code.

Well, using “On Error GoTo 0” make no difference in your code. VBA will simply stop the code and show a message with a description of the error. Then why would I bother to use it? Smart Question. Let’s use the example you have used above in “On Error Resume Next”.

In this code whenever an error will occur VBA will resume to the next line of code and run it and you won’t see any error message. But let’s say you have more lines in your code and you don’t want to surpass those lines if there’s an error in the code.

So, if you enter “On Error GoTo 0” after the second line of code it will restore the VBA’s default error handler which shows error messages each time an error occurs.

3. On Error GoTo [Label]

Think about a place in a building where you can head up in an emergency. In the same way, using “On Error GoTo [Label]”, you can simply create a separate block of code in your main code to deal with an error.

Actually, “On Error GoTo [Label]” is a far better and more convenient way to deal with errors. In the below code, you have “On Error GoTo Oh!Error” now in this line statement the word “Oh!Error” is the label.

If you look at the end of the code where you have a specific starting with the label name and then a code for a message box with a message about the code.

Now, what happens if an error occurs the VBA will jump to the label “Oh!Error” and run the block of code which you have after that label.

But there’s one thing you need to take care of: If an error doesn’t occur even then the label you have in your code will get executed. There are two things you need to do:

  • First, make sure to add your Error label at the end of the code.
  • Second, add an “Exit Sub” before the error label.

With this, you’ll benefit in both situations. Let’s say if an error occurs and VBA jumps to the label you specified there would only be code from the label itself to code. And if an error doesn’t occur “Exit Sub” statement which you have before the label will exit the procedure without executing the error label.

4. On Error GoTo -1

Before we get into this, let me share something with you.  When an error occurs in a code VBA stores that error log in its memory and only clears it when the routine ends.

O VBA! Live in Present

To deal with the second error in a VBA code you need to clear the first error from VBA’s memory. In the below code, you have two “On Error GoTo [Label]” statements that deal with errors from two different blocks of code.

But if you run this code, when the second error VBA won’t jump to the label which you have defined and instead show the error message “Type Mismatch”.

Sub Square_Root()
On Error GoTo myError1
Range("A1").Value = Range("A1").Value ^ (1 / 2)
myError1:
MsgBox "There's some problem with the value you have in the cell A1."
On Error GoTo myError2
Range("A2").Value = Range("A2").Value ^ (1 / 2)
myError2:
MsgBox "There's some problem with the value you have in the cell A2."
End Sub

To fix this problem you can use “On Error GoTo -1” which makes VBA remove the current error from its storage memory.

Sub Square_Root()
 On Error GoTo myError1
 Range("A1").Value = Range("A1").Value ^ (1 / 2)
 myError1:
 MsgBox "There's some problem with the value you have in the cell A1."
 On Error GoTo -1
 On Error GoTo myError2
 Range("A2").Value = Range("A2").Value ^ (1 / 2)
 myError2:
 MsgBox "There's some problem with the value you have in the cell A2."
 End Sub

Now when you run this code, “On Error GoTo -1” removes the error from the memory and VBA deals with the error in the second statement as you want.

What Else Do I Need to Know to Handle Errors in VBA?

Apart from using error handling techniques, there are a few other things that you can use to deal with errors in a better way.

Err Object

When an error occurred while executing of code, you can use the Err object to get details about that error. There are a few properties and methods which you can use with Err object. Let’s learn them one by one.

Properties

Below are the properties which you can use with the Err object:

  • Err.Number: With an error occurred there’s a number stored in the Err Object. In the below code, when occurred the message box will show the error number.  
  • Err.Description: This property shows the description of the error which can help you to understand the reason for the error.
  • Err.Source: This property shows you in which project the error has occurred.
  • Err.HelpContext: This property returns the help context id for the error in the help file.
  • Err.HelpContext: This is a string value for the location of the help file.

Normally when you are dealing with errors using error handling techniques you won’t be using the Err Object that much in your codes. But below is a simple example to use it.

Sub Square_Root()
On Error GoTo myError1
    Range("A1").Value = Sqr(Range("A1").Value)
Exit Sub
myError1:
    MsgBox "There's some problem with the value you have in the cell A1." & vbCrLf & _
                "Error Number: " & Err.Number  & vbCrLf & _
                "Error Description: " & Err.Description
End Sub

When you run the above code, and if an error occurred, it will show a message box with the error number and description of the error.

Methods

With Err Object there are two methods that you can also use.

  • Err.Clear: This method clears the error number and error description from VBA’s memory (It’s different from “On Error GoTo -1” as it doesn’t completely reset the error).
  • Err.Raise: With this method, you can generate a run time error in your code intentionally, and below is the syntax which needs to follow:

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

Quick Tips on Error Handling

Here are a few quick tips which you can use to deal with VBA errors in a better way.

  • Use “On Error Resume Next” only when you know for sure about an error to occur and it’s OK to skip the line of code with an error and it’s safe to skip to the next line.
  • The best way to deal with run-time errors is by using “Error Handler” with “On Error GoTo [Label]”. This ensures that whenever the error occurs you will know about it, but it won’t show that nasty error message.
  • Whenever you use the error handler make sure to use “Exit Sub” before it.

There’s More

Below are some of the links which could be useful for you to learn more about error handling in VBA, make sure to check out all of these:

Type Mismatch (Error 13) | Runtime (Error 1004) | Object Required (Error 424) | Out of Memory (Error 7) | Object Doesn’t Support this Property or Method (Error 438) | Invalid Procedure Call or Argument (Error 5) | Overflow (Error 6) | Automation error (Error 440) | VBA Error 400 | VBA Subscript Out of Range Runtime Error 9

Hello all,

When I call a function from a DLL, written in C++ and compiled in Visual Studio 2015 «Release» mode, I get the runtime error message “Run-time error ’11’: Division by zero” at the function call. However, when I compile as «Debug»,
everything runs fine.

I found out that the «Release» compilation does some name mangling with the called function, while «Debug» doesn’t do that. I found the real exported name through applying «dumpbin» on the DLL. Therefore one needs to use this alias
name in VBA’s Declare-statement in the “Release” case (see below), while for the «Debug» compilation this is not needed. Furthermore, all this is done in a 32-bit environment (Windows 7, Office 2010), if I do that in a 64-bit environment (Windows
10, Office 365), there is no problem.

Does anybody have an idea what is going on here?

Here are the details of the problem:

The DLL “Simulation.dll” is written in C++ and compiled in Visual Studio 2015. The C++ function definition is in the file “source.cpp” which doesn’t have any header file, and reads

double __declspec(dllexport) simulationCPP18(<list of 50 parameters, all either double or double*>)

Now I compile in Visual Studio 2015 “Debug” mode to produce the DLL “Simulation.dll”. I declare the DLL function in VBA through

Declare Function simulationCPP18 _
Lib "Simulation.dll" _
(<list of 50 parameters, all double, some ByVal and some ByRef>) As Double

Running the VBA macro like this, everything works fine and the correct result is reproduced.

However, when I compile in “Release” mode, this first gives the error “Can’t find DLL entry point”. I could resolve this error, by finding out the real exported function name through applying “dumpbin” on “Simulation.dll” . This showed that the function
name was mangled to “?simulationCPP18@@YGNPAN00000000N00000000000NNN00N0N00NNNNNNN@Z”. Now I used this name as function Alias in the declare statement, written as

Declare Function simulationCPP18 _
Lib "Simulation.dll" Alias “?simulationCPP18@@YGNPAN00000000N00000000000NNN00N0N00NNNNNNN@Z" _
(<list of 50 parameters, all double, some ByVal and some ByRef>) As Double

The VBA macro seems to find the entry point now, but throws the error message : “Run-time error ’11’: Division by zero” at the  point of the function call within the VBA macro, where it reads

i = simulationCPP18(<list of 50 parameters>)

Note that there is no explicit division happening at any point close to this function call, nor within the parameters.

Do you know where this different behaviour between “Debug” and “Release” compilation is coming from? Obviously, the mangled function name itself is correctly used, otherwise the Error “Can’t find DLL entry point” would prevail, right?

Thanks for any help on that.

  • Moved by

    Tuesday, June 14, 2016 5:31 PM
    c++ problem/ maybe VBA

  • #1

I am new to VBA programming and am trying to develop a simple code for RCC design. Most of the values are assigned directly from the excel sheet. I am getting this error that says «division by zero».The line within **(red) ** is highlighted while debugging. it seems there is some problem with declaration or looping but i am not being able to identify. Pls help. Thanx in advance. The code is as follows:

<code style=»margin: 0px; padding: 0px; border: 0px; vertical-align: baseline; font-family: Consolas, Menlo, Monaco, ‘Lucida Console’, ‘Liberation Mono’, ‘DejaVu Sans Mono’, ‘Bitstream Vera Sans Mono’, ‘Courier New’, monospace, serif; white-space: inherit; background-image: initial; background-attachment: initial; background-size: initial; background-origin: initial; background-clip: initial; background-position: initial; background-repeat: initial;»>Private Sub CommandButton1_Click() Dim a As Double, b As Double, result As String, Mu As Double
Dim i As Integer, j As Integer, c As Integer, Xu1 As Double, Xu As Double, es As Double, d As Double, f As Double, fs As Double
Dim strain1(1 To 6) As Double, stress1(1 To 6) As Double
a = Range(«E30»).Value
b = Range(«O30»).Value
If a < b Then
result = «Under Reinforced Section»
Mu = Range(«E32»).Value * Range(«E34»).Value
ElseIf a = b Then
result = «Balanced Secction»
Mu = Range(«E32»).Value * Range(«E34»).Value
ElseIf a > b Then
result = «Over Reinforced Section»
j = 31
For i = 1 To 6
strain1(i) = Cells(j, 7)// loop to assign values in array from excel sheet
j = j + 1
Next
j = 31
For i = 1 To 6
stress1(i) = Cells(j, 8)
j = j + 1
Next
c = 1
Xu1 = Range(«O30»).Value// The debugger shows the correct value on the RHS but shows zero on the LHS
d = Range(«E31»).Value
Do While c = 1
Xu = Xu1
**es = 0.0035 * (d — Xu) / (Xu)**// apparently Xu is taking value zero
If Range(«E22»).Value = 250 Then
fs = es * Range(«E23»).Value
f = 0.87 * Range(«E22»).Value
If fs > f Then
fs = f
End If
ElseIf Range(«E22»).Value = 415 Then
f = 0.696 * Range(«E22»).Value / Range(«E23»).Value
If es > f Then
For i = 1 To 6
If es > strain1(i) And es < strain1(i + 1) Then// to locate es in the array and then interpolate
fs = stress1(i) + ((stress1(i + 1) — stress1(i)) / (strain1(i + 1) — strain1(i))) * (es -strain1(i))
End If
Next
ElseIf es < f Then
fs = es * Range(«E23»).Value
End If
Xu1 = Range(«O29»).Value * fs / (0.36 * Range(«E21»).Value * Range(«E16»).Value)
If Xu1 = Xu Then
c = 0
End If
Mu = 0.36 * Range(«E21»).Value * Range(«E16»).Value * Xu1 * Range(«E34»).Value
End If
Loop
End If
Range(«O21»).Value = Mu
MsgBox result
End Sub</code>

Who is Mr Spreadsheet?

Author John Walkenbach was Mr Spreadsheet until his retirement in June 2019.

  • #2

Agreed, Xu looks like it is zero.
Am No VBA expert but looking at the code I’d have to say that the cell O30 from which Xu1 gets its value must be zero.

Or maybe O30 is text and returning zero to your VBA?
Can you confirm O30 is actually a number and not text?

  • #3

yes it is a number. in fact the debugger shows the number when the cursor is on the RHS but shows 0 when the cursor is on Xu1

  • #4

Yes it is a number. in fact the debugger shows the correct value when the cursor is over the RHS but shows 0 when the cursor is over LHS.

  • #5

I think it’s this causing the 0 (at some point)

Code:

Xu1 = Range("O29").Value * fs / (0.36 * Range("E21").Value * Range("E16").Value)

So same question are E21 E23 or E16 text or zero?
If they are all non zero numbers I’d say
this may also be causing the problem somewhere along the line

Code:

fs = stress1(i) + ((stress1(i + 1) - stress1(i)) / (strain1(i + 1) - strain1(i))) * (es -strain1(i))

Best thing is to debug the above values/variables and see if one changes to zero.

  • #6

Is there any problem with declaration of variables. And if the cells had been zero how would it show the correct value on the RHS.
Xu1 = Range(«O29»).Value * fs / (0.36 * Range(«E21»).Value * Range(«E16»).Value)
On the RHS debugger shows the correct value. When on Xu1 it shows 0. How is it possible?

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Divinity original sin ошибка установки
  • Divinity original sin ошибка msvcp120 dll