Меню

Vba обработка ошибок type mismatch

На чтение 8 мин. Просмотров 23.9k.

Mismatch Error

Содержание

  1. Объяснение Type Mismatch Error
  2. Использование отладчика
  3. Присвоение строки числу
  4. Недействительная дата
  5. Ошибка ячейки
  6. Неверные данные ячейки
  7. Имя модуля
  8. Различные типы объектов
  9. Коллекция Sheets
  10. Массивы и диапазоны
  11. Заключение

Объяснение Type Mismatch Error

Type Mismatch Error VBA возникает при попытке назначить значение между двумя различными типами переменных.

Ошибка отображается как:
run-time error 13 – Type mismatch

VBA Type Mismatch Error 13

Например, если вы пытаетесь поместить текст в целочисленную переменную Long или пытаетесь поместить число в переменную Date.

Давайте посмотрим на конкретный пример. Представьте, что у нас есть переменная с именем Total, которая является длинным целым числом Long.

Если мы попытаемся поместить текст в переменную, мы получим Type Mismatch Error VBA (т.е. VBA Error 13).

Sub TypeMismatchStroka()

    ' Объявите переменную типа long integer
    Dim total As Long
    
    ' Назначение строки приведет к Type Mismatch Error
    total = "Иван"
    
End Sub

Давайте посмотрим на другой пример. На этот раз у нас есть переменная ReportDate типа Date.

Если мы попытаемся поместить в эту переменную не дату, мы получим Type Mismatch Error VBA.

Sub TypeMismatchData()

    ' Объявите переменную типа Date
    Dim ReportDate As Date
    
    ' Назначение числа вызывает Type Mismatch Error
    ReportDate = "21-22"
    
End Sub

В целом, VBA часто прощает, когда вы назначаете неправильный тип значения переменной, например:

Dim x As Long

' VBA преобразует в целое число 100
x = 99.66

' VBA преобразует в целое число 66
x = "66"

Тем не менее, есть некоторые преобразования, которые VBA не может сделать:

Dim x As Long

' Type Mismatch Error
x = "66a"

Простой способ объяснить Type Mismatch Error VBA состоит в том, что элементы по обе стороны от равных оценивают другой тип.

При возникновении Type Mismatch Error это часто не так просто, как в этих примерах. В этих более сложных случаях мы можем использовать средства отладки, чтобы помочь нам устранить ошибку.

Использование отладчика

В VBA есть несколько очень мощных инструментов для поиска ошибок. Инструменты отладки позволяют приостановить выполнение кода и проверить значения в текущих переменных.

Вы можете использовать следующие шаги, чтобы помочь вам устранить любую Type Mismatch Error VBA.

  1. Запустите код, чтобы появилась ошибка.
  2. Нажмите Debug в диалоговом окне ошибки. Это выделит строку с ошибкой.
  3. Выберите View-> Watch из меню, если окно просмотра не видно.
  4. Выделите переменную слева от equals и перетащите ее в окно Watch.
  5. Выделите все справа от равных и перетащите его в окно Watch.
  6. Проверьте значения и типы каждого.
  7. Вы можете сузить ошибку, изучив отдельные части правой стороны.

Следующее видео показывает, как это сделать.

На скриншоте ниже вы можете увидеть типы в окне просмотра.

VBA Type Mismatch Watch

Используя окно просмотра, вы можете проверить различные части строки кода с ошибкой. Затем вы можете легко увидеть, что это за типы переменных.

В следующих разделах показаны различные способы возникновения Type Mismatch Error VBA.

Присвоение строки числу

Как мы уже видели, попытка поместить текст в числовую переменную может привести к Type Mismatch Error VBA.

Ниже приведены некоторые примеры, которые могут вызвать ошибку:

Sub TextErrors()

    ' Long - длинное целое число
    Dim l As Long
    l = "a"
    
    ' Double - десятичное число
    Dim d As Double
    d = "a"
    
   ' Валюта - 4-х значное число
    Dim c As Currency
    c = "a"
    
    Dim d As Double
    ' Несоответствие типов, если ячейка содержит текст
    d = Range("A1").Value
    
End Sub

Недействительная дата

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

В следующих примерах кода показаны все допустимые способы назначения даты, за которыми следуют случаи, которые могут привести к Type Mismatch Error VBA.

Sub DateMismatch()

    Dim curDate As Date
    
    ' VBA сделает все возможное для вас
    ' - Все они действительны
    curDate = "12/12/2016"
    curDate = "12-12-2016"
    curDate = #12/12/2016#
    curDate = "11/Aug/2016"
    curDate = "11/Augu/2016"
    curDate = "11/Augus/2016"
    curDate = "11/August/2016"
    curDate = "19/11/2016"
    curDate = "11/19/2016"
    curDate = "1/1"
    curDate = "1/2016"
   
    ' Type Mismatch Error
    curDate = "19/19/2016"
    curDate = "19/Au/2016"
    curDate = "19/Augusta/2016"
    curDate = "August"
    curDate = "Какой-то случайный текст"

End Sub

Ошибка ячейки

Тонкая причина Type Mismatch Error VBA — это когда вы читаете из ячейки с ошибкой, например:

VBA Runtime Error

Если вы попытаетесь прочитать из этой ячейки, вы получите Type Mismatch Error.

Dim sText As String

' Type Mismatch Error, если ячейка содержит ошибку
sText = Sheet1.Range("A1").Value

Чтобы устранить эту ошибку, вы можете проверить ячейку с помощью IsError следующим образом.

Dim sText As String
If IsError(Sheet1.Range("A1").Value) = False Then
    sText = Sheet1.Range("A1").Value
End If

Однако проверка всех ячеек на наличие ошибок невозможна и сделает ваш код громоздким. Лучший способ — сначала проверить лист на наличие ошибок, а если ошибки найдены, сообщить об этом пользователю.

Вы можете использовать следующую функцию, чтобы сделать это:

Function CheckForErrors(rg As Range) As Long

    On Error Resume Next
    CheckForErrors = rg.SpecialCells(xlCellTypeFormulas, xlErrors).Count

End Function

Ниже приведен пример использования этого кода.

Sub DoStuff()

    If CheckForErrors(Sheet1.Range("A1:Z1000")) > 0 Then
        MsgBox "На листе есть ошибки. Пожалуйста, исправьте и запустите макрос снова."
        Exit Sub
    End If
    
    ' Продолжайте здесь, если нет ошибок

End Sub

Неверные данные ячейки

Как мы видели, размещение неверного типа значения в переменной вызывает Type Mismatch Error VBA. Очень распространенная причина — это когда значение в ячейке имеет неправильный тип.

Пользователь может поместить текст, такой как «Нет», в числовое поле, не осознавая, что это приведет к Type Mismatch Error в коде.

VBA Error 13

Если мы прочитаем эти данные в числовую переменную, то получим
Type Mismatch Error VBA.

Dim rg As Range
Set rg = Sheet1.Range("B2:B5")

Dim cell As Range, Amount As Long
For Each cell In rg
    ' Ошибка при достижении ячейки с текстом «Нет»
    Amount = cell.Value
Next rg

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

Function CheckForTextCells(rg As Range) As Long

    ' Подсчет числовых ячеек
    If rg.Count = rg.SpecialCells(xlCellTypeConstants, xlNumbers).Count Then
        CheckForTextCells = True
    End If
    
End Function

Вы можете использовать это так:

Sub IspolzovanieCells()

    If CheckForTextCells(Sheet1.Range("B2:B6").Value) = False Then
        MsgBox "Одна из ячеек не числовая. Пожалуйста, исправьте перед запуском макроса"
        Exit Sub
    End If
    
    ' Продолжайте здесь, если нет ошибок

End Sub

Имя модуля

Если вы используете имя модуля в своем коде, это может привести к
Type Mismatch Error VBA. Однако в этом случае причина может быть не очевидной.

Например, допустим, у вас есть модуль с именем «Module1». Выполнение следующего кода приведет к о
Type Mismatch Error VBA.

Sub IspolzovanieImeniModulya()
    
    ' Type Mismatch Error
    Debug.Print module1

End Sub

VBA Type Mismatch Module Name

Различные типы объектов

До сих пор мы рассматривали в основном переменные. Мы обычно называем переменные основными типами данных.

Они используются для хранения одного значения в памяти.

В VBA у нас также есть объекты, которые являются более сложными. Примерами являются объекты Workbook, Worksheet, Range и Chart.

Если мы назначаем один из этих типов, мы должны убедиться, что назначаемый элемент является объектом того же типа. Например:

Sub IspolzovanieWorksheet()

    Dim wk As Worksheet
    
    ' действительный
    Set wk = ThisWorkbook.Worksheets(1)
    
    ' Type Mismatch Error
    ' Левая сторона - это worksheet - правая сторона - это workbook
    Set wk = Workbooks(1)

End Sub

Коллекция Sheets

В VBA объект рабочей книги имеет две коллекции — Sheets и Worksheets. Есть очень тонкая разница.

  1. Worksheets — сборник рабочих листов в Workbook
  2. Sheets — сборник рабочих листов и диаграммных листов в Workbook
  3.  

Лист диаграммы создается, когда вы перемещаете диаграмму на собственный лист, щелкая правой кнопкой мыши на диаграмме и выбирая «Переместить».

Если вы читаете коллекцию Sheets с помощью переменной Worksheet, она будет работать нормально, если у вас нет рабочей таблицы.

Если у вас есть лист диаграммы, вы получите
Type Mismatch Error VBA.

В следующем коде Type Mismatch Error появится в строке «Next sh», если рабочая книга содержит лист с диаграммой.

Sub SheetsError()

    Dim sh As Worksheet
    
    For Each sh In ThisWorkbook.Sheets
        Debug.Print sh.Name
    Next sh

End Sub

Массивы и диапазоны

Вы можете назначить диапазон массиву и наоборот. На самом деле это очень быстрый способ чтения данных.

Sub IspolzovanieMassiva()

    Dim arr As Variant
    
    ' Присвойте диапазон массиву
    arr = Sheet1.Range("A1:B2").Value
    
    ' Выведите значение в строку 1, столбец 1
    Debug.Print arr(1, 1)

End Sub

Проблема возникает, если ваш диапазон имеет только одну ячейку. В этом случае VBA не преобразует arr в массив.

Если вы попытаетесь использовать его как массив, вы получите
Type Mismatch Error .

Sub OshibkaIspolzovanieMassiva()

    Dim arr As Variant
    
    ' Присвойте диапазон массиву
    arr = Sheet1.Range("A1").Value
    
    ' Здесь будет происходить Type Mismatch Error
    Debug.Print arr(1, 1)

End Sub

В этом сценарии вы можете использовать функцию IsArray, чтобы проверить, является ли arr массивом.

Sub IspolzovanieMassivaIf()

    Dim arr As Variant
    
    ' Присвойте диапазон массиву
    arr = Sheet1.Range("A1").Value
    
    ' Здесь будет происходить Type Mismatch Error
    If IsArray(arr) Then
        Debug.Print arr(1, 1)
    Else
        Debug.Print arr
    End If

End Sub

Заключение

На этом мы завершаем статью об Type Mismatch Error VBA. Если у вас есть ошибка несоответствия, которая не раскрыта, пожалуйста, дайте мне знать в комментариях.

VBA Type Mismatch

Excel VBA Type Mismatch

In this article, we will see an outline on Excel VBA Type Mismatch. This is the most usual thing that we all have faced while working on VBA Macro. Sometimes, when we create a macro, due to the selection of incorrect data types or values assignment, we end up getting the error as Type Mismatch. Such kind of error mostly happens at the time of variable assignment and declaration. VBA Type Mismatch gives the “Run Time Error” message with the error code 13. To avoid such errors it is advised to assign the variables properly with proper selection of data types and objects. Also, we need to understand each data type with the type of values it can hold.

How to Fix Type Mismatch Error in VBA?

We will learn how to fix Type Mismatch Error in Excel by using the VBA Code.

You can download this VBA Type Mismatch Excel Template here – VBA Type Mismatch Excel Template

Example #1 – VBA Type Mismatch

To demonstrate the type mismatch error, we need to open a module. For this, follow the below steps:

Step 1: We will go to the Insert menu tab and select the Module from there.

Insert Module

Step 2: Now write the subprocedure for VBA Type mismatch as shown below. We can choose any name here to define the subprocedure.

Code:

Sub VBA_TypeMismatch()

End Sub

VBA Type Mismatch Example 1-1

Step 3: Now we will define a variable let say “A” as an Integer data type.

Code:

Sub VBA_TypeMismatch()

Dim A As Integer

End Sub

VBA Type Mismatch Example 1-2

Step 4: As we all know, Integer data type only stores numbers and that to Whole Numbers. But, just to demonstrate here we will be assigning a text value to variable A.

Code:

Sub VBA_TypeMismatch()

Dim A As Integer
A = "Ten"

End Sub

Integer Data Type Example 1-3

Step 5: And to see the values stored in variable A we will use the Message box.

Code:

Sub VBA_TypeMismatch()

Dim A As Integer
A = "Ten"
MsgBox A

End Sub

VBA Type Mismatch Example 1-4

Step 6: Now run the code by pressing the F5 key or by clicking on the Play Button. As we can see, we really got the error message as “Run-Time Error ‘13’” as shown below with the additional message as “Type Mismatch”.

VBA Type Mismatch Example 1-5

As we already know that Integer can only store whole numbers. So giving it a text will definitely show the error. If we consider the same code and compiled it before we run it, we would have got this error message earlier also. For directly compiling the code, press the F8 function key.

Step 7: If we assign the correct value incorrect format to the variable we define, we will get the proper output.

Code:

Sub VBA_TypeMismatch()

Dim A As Integer
A = 10
MsgBox A

End Sub

VBA Type Mismatch Example 1-6

Step 8: Run the code by pressing the F5 key or by clicking on the Play Button. We will get the message as 10 which we assigned in variable A.

VBA Type Mismatch Example 1-7

Example #2 – VBA Type Mismatch

Let’s see another example of Type Mismatch. For this, follow the below steps:

Step 1: Write the subprocedure for VBA Type Mismatch.

Code:

Sub VBA_TypeMismatch2()

End Sub

VBA Type Mismatch Example 2-1

Step 2: Again assign a new variable, let’s say “A” as Byte data type.

Code:

Sub VBA_TypeMismatch2()

Dim A As Byte

End Sub

VBA Type Mismatch Example 2-2

Let’s understand the Byte Data type here. Byte can only store the numerical value from 0 to 255. And it doesn’t consider any negative value.

Step 3: Now let’s assign any value other than a number. Here we have considered the text “TEN”.

Code:

Sub VBA_TypeMismatch2()

Dim A As Byte
A = "Ten"

End Sub

VBA Type Mismatch Example 2-3

Step 4: And then we will message box for output.

Code:

Sub VBA_TypeMismatch2()

Dim A As Byte
A = "Ten"
MsgBox A

End Sub

VBA Type Mismatch Example 2-4

Step 5: Run the code by pressing the F5 key or by clicking on the Play Button. And we got the error message again. The message is the same as we got in example-1.

VBA Type Mismatch Example 2-5

Step 6: As we have entered value in incorrect format, so the error message we got as “Type Mismatch”. What if we entered a value that is greater than 255? Let’s consider 1000 here.

Code:

Sub VBA_TypeMismatch2()

Dim A As Byte
A = 1000
MsgBox A

End Sub

VBA Type Mismatch Example 2-6

Step 7: This time we got the error as “Run-Time Error ‘6’” overflow. Which means we have entered the value beyond the allow capacity of selected data type.

Run-Time Error ‘6 Example 2-7

Example #3 – VBA Type Mismatch

Let’s see another example. Here we will try to 2 data types and use them as any mathematical operation. For this, follow the below steps:

Step 1: Write the subprocedure for VBA Type Mismatch.

Code:

Sub VBA_TypeMismatch3()

End Sub

Excel VBA Type Mismatch Example 3-1

Step 2: Now let’s consider 2 variables A and B as Integer.

Code:

Sub VBA_TypeMismatch3()

Dim A As Integer
Dim B As Integer

End Sub

VBA Type Mismatch Example 3-2

Step 3: As we all have seen in the previous example, Integer only allows numbers as a whole. So we will be assigning one numeric value to one of the integers and assign any text to another variable as shown below.

Code:

Sub VBA_TypeMismatch3()

Dim A As Integer
Dim B As Integer
A = 10
B = "Ten"

End Sub

VBA Type Mismatch Example 3-3

Step 4: Let’s multiply the above variables here in the message box.

Code:

Sub VBA_TypeMismatch3()

Dim A As Integer
Dim B As Integer
A = 10
B = "Ten"
MsgBox A * B

End Sub

Message Box Example 3-4

Step 5: After running the code, we will get a message box with the error message “Run-time error ’13’”. It is because we have used one text to variable B and then multiplied A with B.

Run-time error ’13 Example 3-5

Step 6: And if we change the data type from Integer to Long. And also change the format of values.

Code:

Sub VBA_TypeMismatch4()

Dim A As Long
Dim B As Long
A = 10
B = "10"
MsgBox A * B

End Sub

Integer to Long Example 3-6

Step 7: If Run the code by pressing the F5 key or by clicking on the Play Button, this code will be successfully executed. Even if we have kept the value 10 in inverted colons in variable B.

VBA Type Mismatch Example 3-8

Pros of VBA Type Mismatch:

  • We actually get to know the mistake where it happened.
  • Error message is so to the point, that even if we do not compile the code, we will get the point of error in the code.

Things to Remember

  • Even if there is a small bracket where we considered a slightly different value, we will definitely get Type Mismatch Error.
  • Understand the type of data types we are going to use and the values permitted in those data types. This will allow us to avoid such silly errors and run the code successfully.
  • All the basic data types have some constraint of input values. It is better to choose those data types which don’t give such error as the wide range of input such as String, Long, Variant mainly. The rest of the data types have some limitations.
  • Once you are done with coding, it is better to save the code in a Macro Enabled Excel format.

Recommended Articles

This is a guide to VBA Type Mismatch. Here we discuss how to Fix Type Mismatch Error in Excel using VBA code along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA DateDiff
  2. VBA Square Root
  3. VBA SendKeys
  4. VBA Name Worksheet

I created a macro for a file and first it was working fine, but today I’ve been opening and restarting the file and macro hundreds of times and I’m always getting the following error:

Excel VBA Run-time error ’13’ Type mismatch

I didn’t change anything in the macro and don’t know why am I getting the error. Furthermore it takes ages to update the macro every time I put it running (the macro has to run about 9000 rows).

The error is on the line in the between ** **.

VBA:

Sub k()

Dim x As Integer, i As Integer, a As Integer
Dim name As String
name = InputBox("Please insert the name of the sheet")
i = 1
Sheets(name).Cells(4, 58) = Sheets(name).Cells(4, 57)
x = Sheets(name).Cells(4, 57).Value
Do While Not IsEmpty(Sheets(name).Cells(i + 4, 57))
    a = 0
    If Sheets(name).Cells(4 + i, 57) <> x Then
        If Sheets(name).Cells(4 + i, 57) <> 0 Then
            If Sheets(name).Cells(4 + i, 57) = 3 Then
                a = x
                Sheets(name).Cells(4 + i, 58) = Sheets(name).Cells(4 + i, 57) - x
                x = Cells(4 + i, 57) - x
            End If
            **Sheets(name).Cells(4 + i, 58) = Sheets(name).Cells(4 + i, 57) - a**
            x = Sheets(name).Cells(4 + i, 57) - a
        Else
        Cells(4 + i, 58) = ""
        End If
    Else
    Cells(4 + i, 58) = ""
    End If

i = i + 1
Loop

End Sub

I’m using excel 2010 on windows 7.

Vega's user avatar

Vega

27.1k27 gold badges91 silver badges98 bronze badges

asked Jan 16, 2012 at 19:52

Diogo's user avatar

1

You would get a type mismatch if Sheets(name).Cells(4 + i, 57) contains a non-numeric value. You should validate the fields before you assume they are numbers and try to subtract from them.

Also, you should enable Option Strict so you are forced to explicitly convert your variables before trying to perform type-dependent operations on them such as subtraction. That will help you identify and eliminate issues in the future, too.
   Unfortunately Option Strict is for VB.NET only. Still, you should look up best practices for explicit data type conversions in VBA.


Update:

If you are trying to go for the quick fix of your code, however, wrap the ** line and the one following it in the following condition:

If IsNumeric(Sheets(name).Cells(4 + i, 57))
    Sheets(name).Cells(4 + i, 58) = Sheets(name).Cells(4 + i, 57) - a
    x = Sheets(name).Cells(4 + i, 57) - a
End If

Note that your x value may not contain its expected value in the next iteration, however.

answered Jan 16, 2012 at 19:55

Devin Burke's user avatar

Devin BurkeDevin Burke

13.5k11 gold badges54 silver badges81 bronze badges

5

Thank you guys for all your help! Finally I was able to make it work perfectly thanks to a friend and also you!
Here is the final code so you can also see how we solve it.

Thanks again!

Option Explicit

Sub k()

Dim x As Integer, i As Integer, a As Integer
Dim name As String
'name = InputBox("Please insert the name of the sheet")
i = 1
name = "Reserva"
Sheets(name).Cells(4, 57) = Sheets(name).Cells(4, 56)

On Error GoTo fim
x = Sheets(name).Cells(4, 56).Value
Application.Calculation = xlCalculationManual
Do While Not IsEmpty(Sheets(name).Cells(i + 4, 56))
    a = 0
    If Sheets(name).Cells(4 + i, 56) <> x Then
        If Sheets(name).Cells(4 + i, 56) <> 0 Then
            If Sheets(name).Cells(4 + i, 56) = 3 Then
                a = x
                Sheets(name).Cells(4 + i, 57) = Sheets(name).Cells(4 + i, 56) - x
                x = Cells(4 + i, 56) - x
            End If
            Sheets(name).Cells(4 + i, 57) = Sheets(name).Cells(4 + i, 56) - a
            x = Sheets(name).Cells(4 + i, 56) - a
        Else
        Cells(4 + i, 57) = ""
        End If
    Else
    Cells(4 + i, 57) = ""
    End If

i = i + 1
Loop
Application.Calculation = xlCalculationAutomatic
Exit Sub
fim:
MsgBox Err.Description
Application.Calculation = xlCalculationAutomatic
End Sub

bpeterson76's user avatar

bpeterson76

12.9k4 gold badges48 silver badges82 bronze badges

answered Jan 17, 2012 at 16:50

Diogo's user avatar

DiogoDiogo

1511 gold badge1 silver badge5 bronze badges

1

Diogo

Justin has given you some very fine tips 🙂

You will also get that error if the cell where you are performing the calculation has an error resulting from a formula.

For example if Cell A1 has #DIV/0! error then you will get «Excel VBA Run-time error ’13’ Type mismatch» when performing this code

Sheets("Sheet1").Range("A1").Value - 1

I have made some slight changes to your code. Could you please test it for me? Copy the code with the line numbers as I have deliberately put them there.

Option Explicit

Sub Sample()
  Dim ws As Worksheet
  Dim x As Integer, i As Integer, a As Integer, y As Integer
  Dim name As String
  Dim lastRow As Long
10        On Error GoTo Whoa

20        Application.ScreenUpdating = False

30        name = InputBox("Please insert the name of the sheet")

40        If Len(Trim(name)) = 0 Then Exit Sub

50        Set ws = Sheets(name)

60        With ws
70            If Not IsError(.Range("BE4").Value) Then
80                x = Val(.Range("BE4").Value)
90            Else
100               MsgBox "Please check the value of cell BE4. It seems to have an error"
110               GoTo LetsContinue
120           End If

130           .Range("BF4").Value = x

140           lastRow = .Range("BE" & Rows.Count).End(xlUp).Row

150           For i = 5 To lastRow
160               If IsError(.Range("BE" & i)) Then
170                   MsgBox "Please check the value of cell BE" & i & ". It seems to have an error"
180                   GoTo LetsContinue
190               End If

200               a = 0: y = Val(.Range("BE" & i))
210               If y <> x Then
220                   If y <> 0 Then
230                       If y = 3 Then
240                           a = x
250                           .Range("BF" & i) = Val(.Range("BE" & i)) - x

260                           x = Val(.Range("BE" & i)) - x
270                       End If
280                       .Range("BF" & i) = Val(.Range("BE" & i)) - a
290                       x = Val(.Range("BE" & i)) - a
300                   Else
310                       .Range("BF" & i).ClearContents
320                   End If
330               Else
340                   .Range("BF" & i).ClearContents
350               End If
360           Next i
370       End With

LetsContinue:
380       Application.ScreenUpdating = True
390       Exit Sub
Whoa:
400       MsgBox "Error Description :" & Err.Description & vbNewLine & _
         "Error at line     : " & Erl
410       Resume LetsContinue
End Sub

answered Jan 16, 2012 at 23:15

Siddharth Rout's user avatar

Siddharth RoutSiddharth Rout

145k17 gold badges206 silver badges250 bronze badges

3

For future readers:

This function was abending in Run-time error '13': Type mismatch

Function fnIsNumber(Value) As Boolean
  fnIsNumber = Evaluate("ISNUMBER(0+""" & Value & """)")
End Function

In my case, the function was failing when it ran into a #DIV/0! or N/A value.

To solve it, I had to do this:

Function fnIsNumber(Value) As Boolean
   If CStr(Value) = "Error 2007" Then '<===== This is the important line
      fnIsNumber = False
   Else
      fnIsNumber = Evaluate("ISNUMBER(0+""" & Value & """)")
   End If
End Function

answered Jun 21, 2018 at 15:45

cssyphus's user avatar

cssyphuscssyphus

36.6k18 gold badges93 silver badges108 bronze badges

Sub HighlightSpecificValue()

'PURPOSE: Highlight all cells containing a specified values


Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range

'What value do you want to find?
  fnd = InputBox("I want to hightlight cells containing...", "Highlight")

    'End Macro if Cancel Button is Clicked or no Text is Entered
      If fnd = vbNullString Then Exit Sub

Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)

enter code here
Set FoundCell = myRange.Find(what:=fnd, after:=LastCell)

'Test to see if anything was found
  If Not FoundCell Is Nothing Then
    FirstFound = FoundCell.Address

  Else
    GoTo NothingFound
  End If

Set rng = FoundCell

'Loop until cycled through all unique finds
  Do Until FoundCell Is Nothing
    'Find next cell with fnd value
      Set FoundCell = myRange.FindNext(after:=FoundCell)







    'Add found cell to rng range variable
      Set rng = Union(rng, FoundCell)

    'Test to see if cycled through to first found cell
      If FoundCell.Address = FirstFound Then Exit Do


  Loop

'Highlight Found cells yellow

  rng.Interior.Color = RGB(255, 255, 0)

  Dim fnd1 As String
  fnd1 = "Rah"
  'Condition highlighting

  Set FoundCell = myRange.FindNext(after:=FoundCell)



  If FoundCell.Value("rah") Then
      rng.Interior.Color = RGB(255, 0, 0)

  ElseIf FoundCell.Value("Nav") Then

    rng.Interior.Color = RGB(0, 0, 255)



    End If





'Report Out Message
  MsgBox rng.Cells.Count & " cell(s) were found containing: " & fnd

Exit Sub

'Error Handler
NothingFound:
  MsgBox "No cells containing: " & fnd & " were found in this worksheet"

End Sub

Neil's user avatar

Neil

54k8 gold badges60 silver badges72 bronze badges

answered Oct 9, 2015 at 10:10

chetan dubey's user avatar

I had the same problem as you mentioned here above and my code was doing great all day yesterday.

I kept on programming this morning and when I opened my application (my file with an Auto_Open sub), I got the Run-time error ’13’ Type mismatch, I went on the web to find answers, I tried a lot of things, modifications and at one point I remembered that I read somewhere about «Ghost» data that stays in a cell even if we don’t see it.

My code do only data transfer from one file I opened previously to another and Sum it. My code stopped at the third SheetTab (So it went right for the 2 previous SheetTab where the same code went without stopping) with the Type mismatch message. And it does that every time at the same SheetTab when I restart my code.

So I selected the cell where it stopped, manually entered 0,00 (Because the Type mismatch comes from a Summation variables declared in a DIM as Double) and copied that cell in all the subsequent cells where the same problem occurred. It solved the problem. Never had the message again. Nothing to do with my code but the «Ghost» or data from the past. It is like when you want to use the Control+End and Excel takes you where you had data once and deleted it. Had to «Save» and close the file when you wanted to use the Control+End to make sure Excel pointed you to the right cell.

TylerH's user avatar

TylerH

20.4k62 gold badges75 silver badges96 bronze badges

answered Oct 11, 2013 at 19:14

Youbi's user avatar

This error occurs when the input variable type is wrong. You probably have written a formula in Cells(4 + i, 57) that instead of =0, the formula = "" have used. So when running this error is displayed. Because empty string is not equal to zero.

enter image description here

answered Dec 13, 2016 at 21:12

gadolf's user avatar

gadolfgadolf

9879 silver badges19 bronze badges

In this Article

  • VBA Type Mismatch Errors
    • What is a Type Mismatch Error?
    • Mismatch Error Caused by Worksheet Calculation
      • Mismatch Error Caused by Entered Cell Values
      • Mismatch Error Caused by Calling a Function or Sub Routine Using Parameters
      • Mismatch Error Caused by using Conversion Functions in VBA Incorrectly
      • General Prevention of Mismatch Errors
      • Define your variables as Variant Type
      • Use the OnError Command to Handle Errors
      • Use the OnError Command to Supress Errors
      • Converting the Data to a Data Type to Match the Declaration
      • Testing Variables Within Your Code
      • Objects and Mismatch Errors

VBA Type Mismatch Errors

What is a Type Mismatch Error?

A mismatch error can often occur when you run your VBA code.  The error will stop your code from running completely and flag up by means of a message box that this error needs sorting out

Note that if you have not fully tested your code before distribution to users, this error message will be visible to users, and will cause a big loss of confidence in your Excel application.  Unfortunately, users often do very peculiar things to an application and are often things that you as the developer never considered.

A type mismatch error occurs because you have defined a variable using the Dim statement as a certain type e.g. integer, date, and your code is trying to assign a value to the variable which is not acceptable e.g. text string assigned to an integer variable as in this example:

Here is an example:

PIC 01

Click on Debug and the offending line of code will be highlighted in yellow.  There is no option on the error pop-up to continue, since this is a major error and there is no way the code can run any further.

In this particular case, the solution is to change the Dim statement to a variable type that works with the value that you are assigning to the variable. The code will work if you change the variable type to ‘String’, and you would probably want to change the variable name as well.

PIC 02

However, changing the variable type will need your project resetting, and you will have to run your code again right from the beginning again, which can be very annoying if a long procedure is involved

PIC 03

Mismatch Error Caused by Worksheet Calculation

The example above is a very simple one of how a mismatch error can be produced and, in this case, it is easily remedied

However, the cause of mismatch errors is usually far deeper than this, and is not so obvious when you are trying to debug your code.

As an example, suppose that you have written code to pick up a value in a certain position on a worksheet and it contains a calculation dependent other cells within the workbook (B1 in this example)

The worksheet looks like this example, with a formula to find a particular character within a string of text

PIC 04

From the user’s point of view, cell A1 is free format and they can enter any value that they want to.  However, the formula is looking for an occurrence of the character ‘B’, and in this case it is not found so cell B1 has an error value.

The test code below will produce a mismatch error because a wrong value has been entered into cell A1

Sub TestMismatch()
Dim MyNumber As Integer
MyNumber = Sheets("Sheet1").Range("B1").Value
End Sub

The value in cell B1 has produced an error because the user has entered text into cell A1 which does not conform to what was expected and it does not contain the character ‘B’

The code tries to assign the value to the variable ‘MyNumber’ which has been defined to expect an integer, and so you get a mismatch error.

This is one of these examples where meticulously checking your code will not provide the answer. You also need to look on the worksheet where the value is coming from in order to find out why this is happening.

The problem is actually on the worksheet, and the formula in B1 needs changing so that error values are dealt with. You can do this by using the ‘IFERROR’ formula to provide a default value of 0 if the search character is not found

PIC 05

You can then incorporate code to check for a zero value, and to display a warning message to the user that the value in cell A1 is invalid

Sub TestMismatch()
Dim MyNumber As Integer
MyNumber = Sheets("Sheet1").Range("B1").Text
If MyNumber = 0 Then
    MsgBox "Value at cell A1 is invalid", vbCritical
    Exit Sub
End If
End Sub

You could also use data validation (Data Tools group on the Data tab of the ribbon) on the spreadsheet to stop the user doing whatever they liked and causing worksheet errors in the first place. Only allow them to enter values that will not cause worksheet errors.

You could write VBA code based on the Change event in the worksheet to check what has been entered.

Also lock and password protect the worksheet, so that the invalid data cannot be entered

Mismatch Error Caused by Entered Cell Values

Mismatch errors can be caused in your code by bringing in normal values from a worksheet (non-error), but where the user has entered an unexpected value e.g. a text value when you were expecting a number.  They may have decided to insert a row within a range of numbers so that they can put a note into a cell explaining something about the number. After all, the user has no idea how your code works and that they have just thrown the whole thing out of kilter by entering their note.

PIC 06

The example code below creates a simple array called ‘MyNumber’ defined with integer values

The code then iterates through a range of the cells from A1 to A7, assigning the cell values into the array, using a variable ‘Coun’ to index each value

When the code reaches the text value, a mismatch error is caused by this and everything grinds to a halt

By clicking on ‘Debug’ in the error pop-up, you will see the line of code which has the problem highlighted in yellow. By hovering your cursor over any instance of the variable ‘Coun’ within the code, you will be able to see the value of ‘Coun’ where the code has failed, which in this case is 5

Looking on the worksheet, you will see that the 5th cell down has the text value and this has caused the code to fail

PIC 07

You could change your code by putting in a condition that checks for a numeric value first before adding the cell value into the array

Sub TestMismatch()
Dim MyNumber(10) As Integer, Coun As Integer
Coun = 1
Do
    If Coun = 11 Then Exit Do
    If IsNumeric(Sheets("sheet1").Cells(Coun, 1).Value) Then
            MyNumber(Coun) = Sheets("sheet1").Cells(Coun, 1).Value
    Else
            MyNumber(Coun) = 0
    End If
    Coun = Coun + 1
Loop
End Sub

The code uses the ‘IsNumeric’ function to test if the value is actually a number, and if it is then it enters it into the array. If it is not number then it enters the value of zero.

This ensures that the array index is kept in line with the cell row numbers in the spreadsheet.

You could also add code that copies the original error value and location details to an ‘Errors’ worksheet so that the user can see what they have done wrong when your code is run.

The numeric test uses the full code for the cell as well as the code to assign the value into the array.  You could argue that this should be assigned to a variable so as not to keep repeating the same code, but the problem is that you would need to define the variable as a ‘Variant’ which is not the best thing to do.

You also need data validation on the worksheet and to password protect the worksheet.  This will prevent the user inserting rows, and entering unexpected data.

Mismatch Error Caused by Calling a Function or Sub Routine Using Parameters

When a function is called, you usually pass parameters to the function using data types already defined by the function. The function may be one already defined in VBA, or it may be a User Defined function that you have built yourself. A sub routine can also sometimes require parameters

If you do not stick to the conventions of how the parameters are passed to the function, you will get a mismatch error

Sub CallFunction()
Dim Ret As Integer
Ret = MyFunction(3, "test")
End Sub

Function MyFunction(N As Integer, T As String) As String
MyFunction = T
End Function

There are several possibilities here to get a mismatch error

The return variable (Ret) is defined as an integer, but the function returns a string. As soon as you run the code, it will fail because the function returns a string, and this cannot go into an integer variable.  Interestingly, running Debug on this code does not pick up this error.

If you put quote marks around the first parameter being passed (3), it is interpreted as a string, which does not match the definition of the first parameter in the function (integer)

If you make the second parameter in the function call into a numeric value, it will fail with a mismatch because the second parameter in the string is defined as a string (text)

Mismatch Error Caused by using Conversion Functions in VBA Incorrectly

There are a number of conversion functions that your can make use of in VBA to convert values to various data types. An example is ‘CInt’ which converts a string containing a number into an integer value.

If the string to be converted contains any alpha characters then you will get a mismatch error, even if the first part of the string contains numeric characters and the rest is alpha characters e.g. ‘123abc’

General Prevention of Mismatch Errors

We have seen in the examples above several ways of dealing with potential mismatch errors within your code, but there are a number of other ways, although they may not be the best options:

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!

automacro

Learn More

Define your variables as Variant Type

A variant type is the default variable type in VBA. If you do not use a Dim statement for a variable and simply start using it in your code, then it is automatically given the type of Variant.

A Variant variable will accept any type of data, whether it is an integer, long integer, double precision number, boolean, or text value. This sounds like a wonderful idea, and you wonder why everyone does not just set all their variables to variant.

However, the variant data type has several downsides. Firstly, it takes up far more memory than other data types.  If you define a very large array as variant, it will swallow up a huge amount of memory when the VBA code is running, and could easily cause performance issues

Secondly, it is slower in performance generally, than if you are using specific data types.  For example, if you are making complex calculations using floating decimal point numbers, the calculations will be considerably slower if you store the numbers as variants, rather than double precision numbers

Using the variant type is considered sloppy programming, unless there is an absolute necessity for it.

Use the OnError Command to Handle Errors

The OnError command can be included in your code to deal with error trapping, so that if an error does ever occur the user sees a meaningful message instead of the standard VBA error pop-up

Sub ErrorTrap()
Dim MyNumber As Integer
On Error GoTo Err_Handler
MyNumber = "test"
Err_Handler:
MsgBox "The error " & Err.Description & " has occurred"
End Sub

This effectively prevents the error from stopping the smooth running of your code and allows the user to recover cleanly from the error situation.

The Err_Handler routine could show further information about the error and who to contact about it.

From a programming point of view, when you are using an error handling routine, it is quite difficult to locate the line of code the error is on. If you are stepping through the code using F8, as soon as the offending line of code is run, it jumps to the error handling routine, and you cannot check where it is going wrong.

A way around this is to set up a global constant that is True or False (Boolean) and use this to turn the error handling routine on or off using an ‘If’ statement.  When you want to test the error all you have to do is set the global constant to False and the error handler will no longer operate.

Global Const ErrHandling = False
Sub ErrorTrap()
Dim MyNumber As Integer
If ErrHandling = True Then On Error GoTo Err_Handler
MyNumber = "test"
Err_Handler:
MsgBox "The error " & Err.Description & " has occurred"
End Sub

The one problem with this is that it allows the user to recover from the error, but the rest of the code within the sub routine does not get run, which may have enormous repercussions later on in the application

Using the earlier example of looping through a range of cells, the code would get to cell A5 and hit the mismatched error.  The user would see a message box giving information on the error, but nothing from that cell onwards in the range would be processed.

VBA Programming | Code Generator does work for you!

Use the OnError Command to Supress Errors

This uses the ‘On Error Resume Next’ command. This is very dangerous to include in your code as it prevents any subsequent errors being shown.  This basically means that as your code is executing, if an error occurs in a line of code, execution will just move to the next available line without executing the error line, and carry on as normal.

This may sort out a potential error situation, but it will still affect every future error in the code. You may then think that your code is bug free, but in fact it is not and parts of your code are not doing what you think it ought to be doing.

There are situations where it is necessary to use this command, such as if you are deleting a file using the ‘Kill’ command (if the file is not present, there will be an error), but the error trapping should always be switched back on immediately after where the potential error could occur using:

On Error Goto 0

In the earlier example of looping through a range of cells, using ‘On Error Resume Next’, this would enable the loop to continue, but the cell causing the error would not be transferred into the array, and the array element for that particular index would hold a null value.

Converting the Data to a Data Type to Match the Declaration

You can use VBA functions to alter the data type of incoming data so that it matches the data type of the receiving variable.

You can do this when passing parameters to functions.  For example, if you have a number that is held in a string variable and you want to pass it as a number to a function, you can use CInt

There are a number of these conversion functions that can be used, but here are the main ones:

CInt – converts a string that has a numeric value (below + or – 32,768) into an integer value. Be aware that this truncates any decimal points off

CLng – Converts a string that has a large numeric value into a long integer.  Decimal points are truncated off.

CDbl – Converts a string holding a floating decimal point number into a double precision number.  Includes decimal points

CDate – Converts a string that holds a date into a date variable. Partially depends on settings in the Windows Control Panel and your locale on how the date is interpreted

CStr – Converts a numeric or date value into a string

When converting from a string to a number or a date, the string must not contain anything other that numbers or a date.  If alpha characters are present this will produce a mismatch error. Here is an example that will produce a mismatch error:

Sub Test()
MsgBox CInt("123abc")
End Sub

Testing Variables Within Your Code

You can test a variable to find out what data type it is before you assign it to a variable of a particular type.

For example, you could check a string to see if it is numeric by using the ‘IsNumeric’ function in VBA

MsgBox IsNumeric("123test")

This code will return False because although the string begins with numeric characters, it also contains text so it fails the test.

MsgBox IsNumeric("123")

This code will return True because it is all numeric characters

There are a number of functions in VBA to test for various data types, but these are the main ones:

IsNumeric – tests whether an expression is a number or not

IsDate – tests whether an expression is a date or not

IsNull – tests whether an expression is null or not. A null value can only be put into a variant object otherwise you will get an error ‘Invalid Use of Null’. A message box returns a null value if you are using it to ask a question, so the return variable has to be a variant. Bear in mind that any calculation using a null value will always return the result of null.

IsArray – tests whether the expression represents an array or not

IsEmpty – tests whether the expression is empty or not.  Note that empty is not the same as null. A variable is empty when it is first defined but it is not a null value

Surprisingly enough, there is no function for IsText or IsString, which would be really useful

Objects and Mismatch Errors

If you are using objects such as a range or a sheet, you will get a mismatch error at compile time, not at run time, which gives you due warning that your code is not going to work

Sub TestRange()
Dim MyRange As Range, I As Long
Set MyRange = Range("A1:A2")
I = 10
x = UseMyRange(I)
End Sub
Function UseMyRange(R As Range)
End Function

This code has a function called ‘UseMyRange’ and a parameter passed across as a range object. However, the parameter being passed across is a Long Integer which does not match the data type.

When you run VBA code, it is immediately compiled, and you will see this error message:

PIC 08

The offending parameter will be highlighted with a blue background

Generally, if you make mistakes in VBA code using objects you will see this error message, rather than a type mismatch message:

PIC 09

Содержание

  1. Несоответствие типов (ошибка 13)
  2. Поддержка и обратная связь
  3. Как исправить ошибку во время выполнения 13
  4. Обзор «Type mismatch»
  5. Почему происходит ошибка времени выполнения 13?
  6. Типичные ошибки Type mismatch
  7. Создатели Type mismatch Трудности
  8. Разбор ошибки Type Mismatch Error
  9. Объяснение Type Mismatch Error
  10. Использование отладчика
  11. Присвоение строки числу
  12. Недействительная дата
  13. Ошибка ячейки
  14. Неверные данные ячейки
  15. Имя модуля
  16. Различные типы объектов
  17. Коллекция Sheets
  18. Массивы и диапазоны
  19. Заключение

Несоответствие типов (ошибка 13)

Visual Basic может преобразовать и привести большое число значений для присвоений типа данных, которые не были возможны в предыдущих версиях.

Тем не менее, эта ошибка может по-прежнему повторяться и имеет следующие причины и решения:

  • Причина:Переменная или свойство имеют неверный тип. Например, переменная целого типа, не может принимать строковые значения, которые не распознаются как целые числа.

Решение: Попробуйте выполнять задания только между совместимыми типами данных. Например, значение типа Integer всегда можно присвоить типу Long, значение Single — типу Double, а любой тип (за исключением пользовательского) — типу Variant.

  • Причина: В процедуру, требующую отдельное свойство или значение, передан объект.

Решение: Передайте отдельное свойство или вызовите метод, соответствующий объекту.

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

Решение: Укажите выражение, которое будет отображаться.

Причина: Попытка использовать традиционный механизм обработки ошибок Basic со значениями Variant с подтипом Error (10, vbError), например:

Решение: Чтобы воссоздать ошибку, необходимо сопоставить ее с пользовательской или внутренней ошибкой Visual Basic, после чего снова создать ее.

Причина: Значение CVErr не может быть преобразовано в тип Date. Например:

Решение: Используйте оператор Select Case или аналогичную конструкцию, чтобы сопоставить возвращаемое значение CVErr с соответствующим значением.

  • Причина: Во время выполнения эта ошибка указывает на то, что переменная Variant, используемая в выражении, имеет неверный подтип, либо переменная Variant, содержащая массив, используется в операторе Print #.

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

Для получения дополнительной информации выберите необходимый элемент и нажмите клавишу F1 (для Windows) или HELP (для Macintosh).

Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Как исправить ошибку во время выполнения 13

Номер ошибки: Ошибка во время выполнения 13
Название ошибки: Type mismatch
Описание ошибки: Visual Basic is able to convert and coerce many values to accomplish data type assignments that weren’t possible in earlier versions.
Разработчик: Microsoft Corporation
Программное обеспечение: Windows Operating System
Относится к: Windows XP, Vista, 7, 8, 10, 11

Обзор «Type mismatch»

«Type mismatch» часто называется ошибкой во время выполнения (ошибка). Когда дело доходит до Windows Operating System, инженеры программного обеспечения используют арсенал инструментов, чтобы попытаться сорвать эти ошибки как можно лучше. Тем не менее, возможно, что иногда ошибки, такие как ошибка 13, не устранены, даже на этом этапе.

Ошибка 13, рассматриваемая как «Visual Basic is able to convert and coerce many values to accomplish data type assignments that weren’t possible in earlier versions.», может возникнуть пользователями Windows Operating System в результате нормального использования программы. Когда это происходит, конечные пользователи программного обеспечения могут сообщить Microsoft Corporation о существовании ошибки 13 ошибок. Команда программирования может использовать эту информацию для поиска и устранения проблемы (разработка обновления). Чтобы исправить любые документированные ошибки (например, ошибку 13) в системе, разработчик может использовать комплект обновления Windows Operating System.

Почему происходит ошибка времени выполнения 13?

Сбой устройства или Windows Operating System обычно может проявляться с «Type mismatch» в качестве проблемы во время выполнения. Проанализируем некоторые из наиболее распространенных причин ошибок ошибки 13 во время выполнения:

Ошибка 13 Crash — Номер ошибки вызовет блокировка системы компьютера, препятствуя использованию программы. Это возникает, когда Windows Operating System не реагирует на ввод должным образом или не знает, какой вывод требуется взамен.

Утечка памяти «Type mismatch» — последствия утечки памяти Windows Operating System связаны с неисправной операционной системой. Повреждение памяти и другие потенциальные ошибки в коде могут произойти, когда память обрабатывается неправильно.

Ошибка 13 Logic Error — Логические ошибки проявляются, когда пользователь вводит правильные данные, но устройство дает неверный результат. Виновником в этом случае обычно является недостаток в исходном коде Microsoft Corporation, который неправильно обрабатывает ввод.

Как правило, ошибки Type mismatch вызваны повреждением или отсутствием файла связанного Windows Operating System, а иногда — заражением вредоносным ПО. Большую часть проблем, связанных с данными файлами, можно решить посредством скачивания и установки последней версии файла Microsoft Corporation. Помимо прочего, в качестве общей меры по профилактике и очистке мы рекомендуем использовать очиститель реестра для очистки любых недопустимых записей файлов, расширений файлов Microsoft Corporation или разделов реестра, что позволит предотвратить появление связанных с ними сообщений об ошибках.

Типичные ошибки Type mismatch

Частичный список ошибок Type mismatch Windows Operating System:

  • «Ошибка Type mismatch. «
  • «Ошибка программного обеспечения Win32: Type mismatch»
  • «Извините за неудобства — Type mismatch имеет проблему. «
  • «К сожалению, мы не можем найти Type mismatch. «
  • «Type mismatch не найден.»
  • «Ошибка запуска программы: Type mismatch.»
  • «Type mismatch не работает. «
  • «Отказ Type mismatch.»
  • «Type mismatch: путь приложения является ошибкой. «

Обычно ошибки Type mismatch с Windows Operating System возникают во время запуска или завершения работы, в то время как программы, связанные с Type mismatch, выполняются, или редко во время последовательности обновления ОС. Выделение при возникновении ошибок Type mismatch имеет первостепенное значение для поиска причины проблем Windows Operating System и сообщения о них вMicrosoft Corporation за помощью.

Создатели Type mismatch Трудности

Проблемы Type mismatch могут быть отнесены к поврежденным или отсутствующим файлам, содержащим ошибки записям реестра, связанным с Type mismatch, или к вирусам / вредоносному ПО.

В частности, проблемы с Type mismatch, вызванные:

  • Поврежденная или недопустимая запись реестра Type mismatch.
  • Зазаражение вредоносными программами повредил файл Type mismatch.
  • Type mismatch злонамеренно удален (или ошибочно) другим изгоем или действительной программой.
  • Другое программное обеспечение, конфликтующее с Windows Operating System, Type mismatch или общими ссылками.
  • Поврежденная установка или загрузка Windows Operating System (Type mismatch).

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Источник

Разбор ошибки Type Mismatch Error

Объяснение Type Mismatch Error

Type Mismatch Error VBA возникает при попытке назначить значение между двумя различными типами переменных.

Ошибка отображается как:
run-time error 13 – Type mismatch

Например, если вы пытаетесь поместить текст в целочисленную переменную Long или пытаетесь поместить число в переменную Date.

Давайте посмотрим на конкретный пример. Представьте, что у нас есть переменная с именем Total, которая является длинным целым числом Long.

Если мы попытаемся поместить текст в переменную, мы получим Type Mismatch Error VBA (т.е. VBA Error 13).

Давайте посмотрим на другой пример. На этот раз у нас есть переменная ReportDate типа Date.

Если мы попытаемся поместить в эту переменную не дату, мы получим Type Mismatch Error VBA.

В целом, VBA часто прощает, когда вы назначаете неправильный тип значения переменной, например:

Тем не менее, есть некоторые преобразования, которые VBA не может сделать:

Простой способ объяснить Type Mismatch Error VBA состоит в том, что элементы по обе стороны от равных оценивают другой тип.

При возникновении Type Mismatch Error это часто не так просто, как в этих примерах. В этих более сложных случаях мы можем использовать средства отладки, чтобы помочь нам устранить ошибку.

Использование отладчика

В VBA есть несколько очень мощных инструментов для поиска ошибок. Инструменты отладки позволяют приостановить выполнение кода и проверить значения в текущих переменных.

Вы можете использовать следующие шаги, чтобы помочь вам устранить любую Type Mismatch Error VBA.

  1. Запустите код, чтобы появилась ошибка.
  2. Нажмите Debug в диалоговом окне ошибки. Это выделит строку с ошибкой.
  3. Выберите View-> Watch из меню, если окно просмотра не видно.
  4. Выделите переменную слева от equals и перетащите ее в окно Watch.
  5. Выделите все справа от равных и перетащите его в окно Watch.
  6. Проверьте значения и типы каждого.
  7. Вы можете сузить ошибку, изучив отдельные части правой стороны.

Следующее видео показывает, как это сделать.

На скриншоте ниже вы можете увидеть типы в окне просмотра.

Используя окно просмотра, вы можете проверить различные части строки кода с ошибкой. Затем вы можете легко увидеть, что это за типы переменных.

В следующих разделах показаны различные способы возникновения Type Mismatch Error VBA.

Присвоение строки числу

Как мы уже видели, попытка поместить текст в числовую переменную может привести к Type Mismatch Error VBA.

Ниже приведены некоторые примеры, которые могут вызвать ошибку:

Недействительная дата

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

В следующих примерах кода показаны все допустимые способы назначения даты, за которыми следуют случаи, которые могут привести к Type Mismatch Error VBA.

Ошибка ячейки

Тонкая причина Type Mismatch Error VBA — это когда вы читаете из ячейки с ошибкой, например:

Если вы попытаетесь прочитать из этой ячейки, вы получите Type Mismatch Error.

Чтобы устранить эту ошибку, вы можете проверить ячейку с помощью IsError следующим образом.

Однако проверка всех ячеек на наличие ошибок невозможна и сделает ваш код громоздким. Лучший способ — сначала проверить лист на наличие ошибок, а если ошибки найдены, сообщить об этом пользователю.

Вы можете использовать следующую функцию, чтобы сделать это:

Ниже приведен пример использования этого кода.

Неверные данные ячейки

Как мы видели, размещение неверного типа значения в переменной вызывает Type Mismatch Error VBA. Очень распространенная причина — это когда значение в ячейке имеет неправильный тип.

Пользователь может поместить текст, такой как «Нет», в числовое поле, не осознавая, что это приведет к Type Mismatch Error в коде.

Если мы прочитаем эти данные в числовую переменную, то получим
Type Mismatch Error VBA.

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

Вы можете использовать это так:

Имя модуля

Если вы используете имя модуля в своем коде, это может привести к
Type Mismatch Error VBA. Однако в этом случае причина может быть не очевидной.

Например, допустим, у вас есть модуль с именем «Module1». Выполнение следующего кода приведет к о
Type Mismatch Error VBA.

Различные типы объектов

До сих пор мы рассматривали в основном переменные. Мы обычно называем переменные основными типами данных.

Они используются для хранения одного значения в памяти.

В VBA у нас также есть объекты, которые являются более сложными. Примерами являются объекты Workbook, Worksheet, Range и Chart.

Если мы назначаем один из этих типов, мы должны убедиться, что назначаемый элемент является объектом того же типа. Например:

Коллекция Sheets

В VBA объект рабочей книги имеет две коллекции — Sheets и Worksheets. Есть очень тонкая разница.

  1. Worksheets — сборник рабочих листов в Workbook
  2. Sheets — сборник рабочих листов и диаграммных листов в Workbook

Лист диаграммы создается, когда вы перемещаете диаграмму на собственный лист, щелкая правой кнопкой мыши на диаграмме и выбирая «Переместить».

Если вы читаете коллекцию Sheets с помощью переменной Worksheet, она будет работать нормально, если у вас нет рабочей таблицы.

Если у вас есть лист диаграммы, вы получите
Type Mismatch Error VBA.

В следующем коде Type Mismatch Error появится в строке «Next sh», если рабочая книга содержит лист с диаграммой.

Массивы и диапазоны

Вы можете назначить диапазон массиву и наоборот. На самом деле это очень быстрый способ чтения данных.

Проблема возникает, если ваш диапазон имеет только одну ячейку. В этом случае VBA не преобразует arr в массив.

Если вы попытаетесь использовать его как массив, вы получите
Type Mismatch Error .

В этом сценарии вы можете использовать функцию IsArray, чтобы проверить, является ли arr массивом.

Заключение

На этом мы завершаем статью об Type Mismatch Error VBA. Если у вас есть ошибка несоответствия, которая не раскрыта, пожалуйста, дайте мне знать в комментариях.

Источник

Contents

  • 1 VBA Type Mismatch Explained
  • 2 VBA Type Mismatch YouTube Video
  • 3 How to Locate the Type Mismatch Error
  • 4 Assigning a string to a numeric
  • 5 Invalid date
  • 6 Cell Error
  • 7 Invalid Cell Data
  • 8 Module Name
  • 9 Different Object Types
  • 10 Sheets Collection
  • 11 Array and Range
  • 12 Conclusion
  • 13 What’s Next?

VBA Type Mismatch Explained

A VBA Type Mismatch Error occurs when you try to assign a value between two different variable types.

The error appears as “run-time error 13 – Type mismatch”.

VBA Type Mismatch Error 13

For example, if you try to place text in a Long integer variable or you try to place text in a Date variable.

Let’s look at a concrete example. Imagine we have a variable called Total which is a Long integer.

If we try to place text in the variable we will get the VBA Type mismatch error(i.e. VBA Error 13).

' https://excelmacromastery.com/
Sub TypeMismatchString()

    ' Declare a variable of type long integer
    Dim total As Long
    
    ' Assigning a string will cause a type mismatch error
    total = "John"
    
End Sub

Let’s look at another example. This time we have a variable ReportDate of type Date.

If we try to place a non-date in this variable we will get a VBA Type mismatch error

' https://excelmacromastery.com/
Sub TypeMismatchDate()

    ' Declare a variable of type Date
    Dim ReportDate As Date
    
    ' Assigning a number causes a type mismatch error
    ReportDate = "21-22"
    
End Sub

In general, VBA is very forgiving when you assign the wrong value type to a variable e.g.

Dim x As Long

' VBA will convert to integer 100
x = 99.66

' VBA will convert to integer 66
x = "66"

However, there are some conversions that VBA cannot do

Dim x As Long

' Type mismatch error
x = "66a"

A simple way to explain a VBA Type mismatch error, is that the items on either side of the equals evaluate to a different type.

When a Type mismatch error occurs it is often not as simple as these examples. For these more complex cases we can use the Debugging tools to help us resolve the error.

VBA Type Mismatch YouTube Video

Don’t forget to check out my YouTube video on the Type Mismatch Error here:

How to Locate the Type Mismatch Error

The most important thing to do when solving the Type Mismatch error is to, first of all, locate the line with the error and then locate the part of the line that is causing the error.

If your code has Error Handling then it may not be obvious which line has the error.

If the line of code is complex then it may not be obvious which part is causing the error.

The following video will show you how to find the exact piece of code that causes a VBA Error in under a minute:

The following sections show the different ways that the VBA Type Mismatch error can occur.

Assigning a string to a numeric

As we have seen, trying to place text in a numeric variable can lead to the VBA Type mismatch error.

Below are some examples that will cause the error

' https://excelmacromastery.com/
Sub TextErrors()

    ' Long is a long integer
    Dim l As Long
    l = "a"
    
    ' Double is a decimal number
    Dim d As Double
    d = "a"
    
    ' Currency is a 4 decimal place number
    Dim c As Currency
    c = "a"
    
    Dim d As Double
    ' Type mismatch if the cell contains text
    d = Range("A1").Value
    
End Sub

Invalid date

VBA is very flexible when it comes to assigning a date to a date variable. If you put the month in the wrong order or leave out the day, VBA will still do it’s best to accommodate you.

The following code examples show all the valid ways to assign a date followed by the cases that will cause a VBA Type mismatch error.

' https://excelmacromastery.com/
Sub DateMismatch()

    Dim curDate As Date
    
    ' VBA will do it's best for you
    ' - These are all valid
    curDate = "12/12/2016"
    curDate = "12-12-2016"
    curDate = #12/12/2016#
    curDate = "11/Aug/2016"
    curDate = "11/Augu/2016"
    curDate = "11/Augus/2016"
    curDate = "11/August/2016"
    curDate = "19/11/2016"
    curDate = "11/19/2016"
    curDate = "1/1"
    curDate = "1/2016"
   
    ' Type Mismatch
    curDate = "19/19/2016"
    curDate = "19/Au/2016"
    curDate = "19/Augusta/2016"
    curDate = "August"
    curDate = "Some Random Text"

End Sub

Cell Error

A subtle cause of the VBA Type Mismatch error is when you read from a cell that has an error e.g.

VBA Runtime Error

If you try to read from this cell you will get a type mismatch error

Dim sText As String

' Type Mismatch if the cell contains an error
sText = Sheet1.Range("A1").Value

To resolve this error you can check the cell using IsError as follows.

Dim sText As String
If IsError(Sheet1.Range("A1").Value) = False Then
    sText = Sheet1.Range("A1").Value
End If

However, checking all the cells for errors is not feasible and would make your code unwieldy. A better way is to check the sheet for errors first and if errors are found then inform the user.

You can use the following function to do this

Function CheckForErrors(rg As Range) As Long

    On Error Resume Next
    CheckForErrors = rg.SpecialCells(xlCellTypeFormulas, xlErrors).Count

End Function

The following is an example of using this code

' https://excelmacromastery.com/
Sub DoStuff()

    If CheckForErrors(Sheet1.Range("A1:Z1000")) > 0 Then
        MsgBox "There are errors on the worksheet. Please fix and run macro again."
        Exit Sub
    End If
    
    ' Continue here if no error

End Sub

Invalid Cell Data

As we saw, placing an incorrect value type in a variable causes the ‘VBA Type Mismatch’ error. A very common cause is when the value in a cell is not of the correct type.

A user could place text like ‘None’ in a number field not realizing that this will cause a Type mismatch error in the code.

VBA Error 13

If we read this data into a number variable then we will get a ‘VBA Type Mismatch’ error error.

Dim rg As Range
Set rg = Sheet1.Range("B2:B5")

Dim cell As Range, Amount As Long
For Each cell In rg
    ' Error when reaches cell with 'None' text
    Amount = cell.Value
Next rg

You can use the following function to check for non numeric cells before you use the data

Function CheckForTextCells(rg As Range) As Long

    ' Count numeric cells
    If rg.Count = rg.SpecialCells(xlCellTypeConstants, xlNumbers).Count Then
        CheckForTextCells = True
    End If
    
End Function

You can use it like this

' https://excelmacromastery.com/
Sub UseCells()

    If CheckForTextCells(Sheet1.Range("B2:B6").Value) = False Then
        MsgBox "One of the cells is not numeric. Please fix before running macro"
        Exit Sub
    End If
    
    ' Continue here if no error

End Sub

Module Name

If you use the Module name in your code this can cause the VBA Type mismatch to occur. However in this case the cause may not be obvious.

For example let’s say you have a Module called ‘Module1’. Running the following code would result in the VBA Type mismatch error.

' https://excelmacromastery.com/
Sub UseModuleName()
    
    ' Type Mismatch
    Debug.Print module1

End Sub

VBA Type Mismatch Module Name

Different Object Types

So far we have been looking mainly at variables. We normally refer to variables as basic data types.

They are used to store a single value in memory.

In VBA we also have objects which are more complex. Examples are the Workbook, Worksheet, Range and Chart objects.

If we are assigning one of these types we must ensure the item being assigned is the same kind of object. For Example

' https://excelmacromastery.com/
Sub UsingWorksheet()

    Dim wk As Worksheet
    
    ' Valid
    Set wk = ThisWorkbook.Worksheets(1)
    
    ' Type Mismatch error
    ' Left side is a worksheet - right side is a workbook
    Set wk = Workbooks(1)

End Sub

Sheets Collection

In VBA, the workbook object has two collections – Sheets and Worksheets. There is a very subtle difference

  1. Worksheets – the collection of worksheets in the Workbook
  2. Sheets – the collection of worksheets and chart sheets in the Workbook

A chart sheet is created when you move a chart to it’s own sheet by right-clicking on the chart and selecting Move.

If you read the Sheets collection using a Worksheet variable it will work fine if you don’t have a chart sheet in your workbook.

If you do have a chart sheet then you will get the VBA Type mismatch error.

In the following code, a Type mismatch error will appear on the Next sh line if the workbook contains a chart sheet.

' https://excelmacromastery.com/
Sub SheetsError()

    Dim sh As Worksheet
    
    For Each sh In ThisWorkbook.Sheets
        Debug.Print sh.Name
    Next sh

End Sub

Array and Range

You can assign a range to an array and vice versa. In fact this is a very fast way of reading through data.

' https://excelmacromastery.com/
Sub UseArray()

    Dim arr As Variant
    
    ' Assign the range to an array
    arr = Sheet1.Range("A1:B2").Value
    
    ' Print the value a row 1, column 1
    Debug.Print arr(1, 1)

End Sub

The problem occurs if your range has only one cell. In this case, VBA does not convert arr to an array.

If you try to use it as an array you will get the Type mismatch error

' https://excelmacromastery.com/
Sub UseArrayError()

    Dim arr As Variant
    
    ' Assign the range to an array
    arr = Sheet1.Range("A1").Value
    
    ' Type mismatch will occur here
    Debug.Print arr(1, 1)

End Sub

In this scenario, you can use the IsArray function to check if arr is an array

' https://excelmacromastery.com/
Sub UseArrayIf()

    Dim arr As Variant
    
    ' Assign the range to an array
    arr = Sheet1.Range("A1").Value
    
    ' Type mismatch will occur here
    If IsArray(arr) Then
        Debug.Print arr(1, 1)
    Else
        Debug.Print arr
    End If

End Sub

Conclusion

This concludes the post on the VBA Type mismatch error. If you have a mismatch error that isn’t covered then please let me know in the comments.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Type mismatch error, or we can also call it Error code 13, occurs when we assign a value to a variable that is not of its data type. For example, if we provide a decimal or long value to an Integer data type variable, we will encounter this Type mismatch error when we run the code, which shows as error code 13.

VBA Type Mismatch Error in excel is a type of “Run Time Error,” and it is the number 13 error in this category.

To start learning in VBA and for beginners, it is hard to find the error thrown by the VBA codes. Remember, VBA is not throwing an error. Rather, it is just highlighting our mistakes while writing the code.

We usually declare variables. We assign data types to them. When we assign a value to those variables, we need to remember what kind of data it can hold. If the assigned value is not as per the data type, we will get “Run-time error ’13’: Type mismatch.”

Table of contents
  • What is VBA Type Mismatch Error?
    • How to Fix VBA Type Mismatch Run-time Error 13?
      • VBA Type Mismatch – Example #1
      • VBA Type Mismatch – Example #2
      • VBA Type Mismatch – Example #3
      • VBA Type Mismatch – Example #4
    • Recommended Articles

VBA Type Mismatch Error

You are free to use this image on you website, templates, etc., Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Type Mismatch Error (wallstreetmojo.com)

How to Fix VBA Type Mismatch Run-time Error 13?

Let us see some examples to understand this VBA Type Mismatch Error.

You can download this VBA Type Mismatch Excel Template here – VBA Type Mismatch Excel Template

VBA Type Mismatch – Example #1

Look at the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

Code:

Sub Type_MisMatch_Example1()

Dim k As Byte

k = "Hiii"

MsgBox k

End Sub

vba mismatch example 1.1

We have declared the variable “k” as Byte.

The variable “k” can hold values from 0 to 255. But in the next line, we have assigned the value for the variable “k” as “Hiii.”

The data type cannot hold a text’s value, so the Type Mismatch Error comes.

vba mismatch example 1.2

VBA Type Mismatch – Example #2

Now, look at one more example with a different data type. Look at the below code.

Code:

Sub Type_MisMatch_Example2()

Dim x As Boolean

x = 4556

MsgBox x

End Sub

vba mismatch example 2.1

We have declared the variable “x” as Boolean.

Boolean is a data typeBoolean is an inbuilt data type in VBA used for logical references or logical variables. The value this data type holds is either TRUE or FALSE and is used for logical comparison. The declaration of this data type is similar to all the other data types.read more that can hold the value of either TRUE or FALSE.

In the above code, we have assigned a value of 4556, which is not as per the data type values of TRUE or FALSE.

When we run this code, you would expect a type mismatch error, but see what happens when we run this code.

vba mismatch example 2.2

You must wonder why this is not “Run-time error ’13’ ” or a type mismatch.

The reason for this is excel treats all the numbers as TRUE except zero. So, zero value will be treated as FALSE. So that is why we got the result as TRUE instead of an error.

Now see, we will assign a numerical value with text.

Code:

Sub Type_MisMatch_Example2()

Dim x As Boolean

x = "4556a"

MsgBox x

End Sub

vba mismatch example 2.3

It will throw “Run-time error ’13’: Type mismatch.”

vba mismatch example 2.4

VBA Type Mismatch – Example #3

Now, look at the below code for this example.

Code:

Sub Type_MisMatch_Example4()

Dim x As Integer
Dim y As String

x = 45
y = "2019 Jan"

MsgBox x + y

End Sub

example 3.1

Variable “x” is an Integer data type, and “y” is a String data type.

X = 45 and y = 2019 Jan.

In the message box, we have added x + y.

But this is not the perfect code because we cannot add numbers with string texts. As a result, we will encounter “Run-time error ’13.’ “

example 3.2

VBA Type Mismatch – Example #4

Exceptional Cases

There are situations where excel forgives the erroneous data assigned to the variable data type. For example, look at the below code.

Code:

Sub Type_MisMatch_Example3()

Dim x As Long
Dim y As Long

x = 58.85

y = "85"

MsgBox x & vbNewLine & y

End Sub

example 4.1

Two declared variables are “x” and “y.”

For this variable, the assigned data type is “Long.”

The long data type accepts only whole numbers, not decimal values.

So, the general perception is to get “Run-time error 13′ ” of type mismatch error.

But let us see what happens when we run this code

example 4.2

We got the values 59 and 85.

VBA will convert the decimal value 58.85 to the nearest integer value. Even though numbers enclosed with double quotes, it only converts to the integer value.

Recommended Articles

This article has been a guide to VBA Type Mismatch. Here, we discussed VBA Type Mismatch “Run-time error ’13’ ‘ in VBA with examples and a downloadable Excel template. Below are some useful articles related to VBA: –

  • Data Type in Excel VBA
  • What is Type Statement in Excel VBA?
  • What is the Integer Data Type?
  • VBA Select Case

Home / VBA / VBA Type Mismatch Error (Error 13)

Type Mismatch (Error 13) occurs when you try to specify a value to a variable that doesn’t match with its data type. In VBA, when you declare a variable you need to define its data type, and when you specify a value that is different from that data type you get the type mismatch error 13.

In this tutorial, we will see what the possible situations are where runtime error 13 can occurs while executing a code.

Type Mismatch Error with Date

In VBA, there is a specific data type to deal with dates and sometimes it happens when you using a variable to store a date and somehow the value you specify is different.

In the following code, I have declared a variable as the date and then I have specified the value from cell A1 where I am supposed to have a date only. But as you can see the date that I have in cell one is not in the correct format VBA is not able to identify it as a date.

Sub myMacro()
Dim iVal As Date
iVal = Range("A1").Value
End Sub

Type Mismatch Error with Number

You’re gonna have you can have the same error while dealing with numbers where you get a different value when you trying to specify a number to a variable.

In the following example, you have an error in cell A1 which is supposed to be a numeric value. So when you run the code, VBA shows you the runtime 13 error because it cannot identify the value as a number.

Sub myMacro()
Dim iNum As Long
iNum = Range("A6").Value
End Sub

Runtime Error 6 Overflow

In VBA, there are multiple data types to deal with numbers and each of these data types has a range of numbers that you can assign to it. But there is a problem when you specify a number that is out of the range of the data type.

In that case, we will show you runtime error 6 overflow which indicates you need to change the data type and the number you have specified is out of the range.

Other Situations When it can Occurs

There might be some other situations in that you could face the runtime error 14: Type Mismatch.

  1. When you assign a range to an array but that range only consists of a single cell.
  2. When you define a variable as an object but by writing the code you specify a different object to that variable.
  3. When you specify a variable as a worksheet but use sheets collection in the code or vice versa.

How to Fix Type Mismatch (Error 13)

The best way to deal with this error is to use to go to the statement to run a specific line of code or show a message box to the user when the error occurs. But you can also check the court step by step before executing it. For this, you need to use VBA’s debug tool, or you can also use the shortcut key F8.

There’s More VBA Errors

Subscript Out of Range (Error 9) | 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

Make sure to check out this VBA Error Handling technique and if you want to learn more don’t forget to jump to this VBA Tutorial.

Хитрости »

21 Март 2015              92239 просмотров


Очень часто начинающие работать в VBA сталкиваются с различными ошибками, которые выдает код в момент выполнения. Если не знать как поступить в данном случае – то очень сложно будет исправить код быстро, а то и вообще невозможно будет определить причину ошибки без помощи более «продвинутых» пользователей. Новички зачастую делают правки наугад, что может порождать иные ошибки, а это в свою очередь не только затрудняет поиск первоначальной ошибки, но и может привести к невозможности исправить код вообще. Поэтому в этой статье я решил описать как производить отладку кода и определять ошибки.
Чтобы описанное в статье можно было сразу опробовать в практике советую скачать файл пример:

  Пример таблицы и кода (35,5 KiB, 2 817 скачиваний)


Что будет рассмотрено:

  • Способы отладки кода в момент появления ошибки
  • Использование окон Locals и Watches для отладки
  • Пошаговая отладка кода — что это такое, как и когда применять
  • Ошибок нет, но код все равно не выполняется

Помимо этого в конце статьи можно скачать файл с кодами ошибок VBA и их расшифровками.

Исходные данные
Допустим, имеется простая таблица
Таблица данных
И код, который должен пройтись по каждой строке таблицы, перемножить цену (столбец Цена) на количество (столбец Продажи шт), просуммировать перемноженные данные и вывести результирующую сумму в ячейку В17:

Option Explicit
Sub PrimitiveCode()
    Dim lr As Long, dblSumm As Double, dblIncr As Double
    'цикл от первой строки таблицы до последней
    For lr = 1 To 14
        'перемножение Цены на Количество (C*E)
        dblIncr = Cells(l, 3).Value * Cells(lr, 5).Value
        'прибавление результата к переменной общей суммы
        dblSumm = dblSumm + dblIncr
    Next
    'выводим результат в ячейку B17
    Cells(17, 2).Value = dblSumm
End Sub
Отладка кода в момент появления ошибки

Если посмотреть на код выше, то опытный программист VBA сразу поймет, что в таком виде код работать не будет – не выполнится и одна строка. Сразу появится ошибка:
Variable not defined

Ошибка означает, что внутри кода есть переменная, которая ранее не была объявлена.
Сама переменная, которую VBA считает не объявленной будет выделена:
Не объявленная переменная
Подробнее об этой ошибке и её причинах можно почитать в статье: Variable not defined или что такое Option Explicit и зачем оно нужно?
Если кратко, то переменной l нет среди объявленных переменных(Dim l As) и мы не можем её использовать. В данном случае это опечатка и там должна быть lr, а не l. Исправляем переменную и код будет выглядеть так:

Sub PrimitiveCode()
    Dim lr As Long, dblSumm As Double, dblIncr As Double
    'цикл от первой строки таблицы до последней
    For lr = 1 To 14
        'перемножение Цены на Количество (C*E)
        dblIncr = Cells(lr, 3).Value * Cells(lr, 5).Value
        'прибавление результата к переменной общей суммы
        dblSumm = dblSumm + dblIncr
    Next
    'выводим результат в ячейку B17
    Cells(17, 2).Value = dblSumm
End Sub

С виду код теперь выполнен правильно и ошибок вызывать не должен. Однако, если его попытаться выполнить опять получим ошибку – на этот раз ошибку типов данных(Type Mismatch):
Type Mismatch
В момент появления главное нажать Debug, а не End (если будет желание прочитать про тип ошибки подробнее – можно еще нажать Help, текст будет на английском). VBA подсветит желтым строку, вычисления или операции в которой вызывают ошибку:
Строка ошибки
Теперь самый важный этап – необходимо определить причину ошибки. С виду все хорошо – одна ячейка перемножается на другую. Без опыта сложно сходу понять, что это ошибка типов данных, хоть VBA прямо об этом говорит(Type Mismatch – в переводе «Несовпадение типов»). Поэтому самое надежное в этом случае – это определить значение каждой составляющей той строки, в которой возникла ошибка. В случае с кодом выше можно воспользоваться двумя методами:

  1. Навести курсор мыши на любую переменную(dblSum, lr) и посмотреть всплывающую подсказку, которая показывает имя переменной и её текущее значение:
    Значение переменной
    После этого переходим на лист с таблицей и смотрим, какое значение в ячейке первой строки третьего столбца(Cells(1,3)). Там значение Закуп цена, что явно не является числом. Следовательно перемножить его нельзя, т.к. это текст. Отсюда и ошибка типов – с текстом нельзя производить математические операции. Для вычислений предполагается в данном случае числовой тип данных(Integer,Long,Double).
  2. Узнать сразу значение ячейки Cells(lr, 3).Value и ячейки Cells(lr, 5).Value. Наведение курсора мыши в данном случае не даст результата. Как правило наведение курсора мыши не имеет эффекта если это не объявленные как переменные объекты (как в этом случае — Cells). Такие объекты не всегда могут быть вычислены в памяти в момент отладки. Поэтому чтобы просмотреть значение ячейки сначала необходимо отобразить окно Immediate(отобразить можно сочетанием клавиш Ctrl+G или через меню ViewImmediate Window). Затем скопировать полностью нужную переменную(Cells(i, 3).Value) и в окне Immediate написать:
    ?
    и после вопр.знака вставить скопированное. Должно получиться:
    ?Cells(i, 3).Value
    И нажать Enter. Строкой ниже в этом окне будет выведено значение для объекта(если оно может быть получено):
    Значение в окне Immediate
    По сути результат будет как и в первом примере – мы увидим, что в ячейке текст. Чем второй метод лучше первого? Тем, что таким образом можно сразу получить значение, не переходя на лист и не выискивая нужный номер строки. Ведь это в примере он равен 1, в реальности же строка может быть и 24451.

Окна Locals и Watches

Так же для отслеживания значений переменных очень удобно использовать окно Locals и окно Watches.

Окно Locals

Окно Locals отображает все локальные переменные, задействованные в выполняемой в настоящий момент процедуре:
Locals Window
Как видно в этом окне отображается имя переменной, её тип и значение. Все хорошо, но в этом окне отображаются исключительно локальные переменные, объявленные на уровне модуля. Переменных других модулей, объявленные как Public и используемые в текущей процедуре там не отображаются. Подробнее про видимость переменных можно узнать в статье: Что такое переменная и как правильно её объявить?

Окно Watches
Окно Watches представляет большую ценность – в это окно можно просто «перетащить» нужную переменную или объект и в этом окне будут отражены все данные об имени переменной, её типе и текущем значении:
Watches Window
Теперь рассмотрим чуть подробнее как перетаскивать в это окно данные. На примере кода выше:

  • Выделяем Cells(i, 3).Value
  • Не снимая выделения наводим курсор мыши на это выделение
  • Зажимаем левую кнопку мыши и не отпуская её переносим курсор в любое место окна Watches

Все, данные по переменной загружены и доступны для просмотра. По сути все умеют это делать — процесс очень схож с обычным перемещением файлов и папок по рабочему столу. Выделили и с зажатой левой кнопкой мыши перенесли в нужное место.
В чем еще один плюс этого окна – в этом окне можно оставлять эти значения и просматривать в моменты пошаговой отладки только занесенные в это окно переменные(про пошаговую отладку будет рассказано ниже). Если вдруг какая-то переменная/объект стали не нужны для постоянного отслеживания их данных – можно удалить их из окна Watches, чтобы не мешалась. Для этого выделяем переменную-правая кнопка мыши – Delete Watch. Так же можно поиграть с иными пунктами, наибольший интерес из которых на мой взгляд, представляет пункт Edit Watch. После его нажатия появится окно
Edit Watch
Самые основные пункты в этом окне, важные для отладки:

  • Break Then value Changes. Если его установить, VBA будет отслеживать значение этой переменной и останавливать код при любом изменении значения переменной. Это может пригодится для отслеживания значений в циклах
  • Break Then value Is True – пункт пригодится для переменных с типом Boolean или для логических выражений. Как только переменная или результат выражения примет значение True – код будет остановлен на этой строке.
    Например, необходимо остановить код, если номер строки будет равен 10(т.е. переменная lr примет значение 10). Тогда выражение будет иметь вид:

    If lr = 10 Then
    'код
    End if

    Тогда надо будет выделить в строке If lr = 10 Then само условное выражение lr = 10, перенести её в окно Watches, выделить строку в окне Watches с этим выражением, нажать правую кнопку мыши и выбрать Edit Watch. Выбрать в окне Break Then value Is True. Теперь как только переменная lr достигнет значения 10(т.е. обрабатываться будет 10-я строка таблицы) – код остановится и строка с выражением будет выделена желтым. Можно будет проанализировать другие переменные или продолжить выполнение кода в пошаговом режиме(см.далее).


Пошаговая отладка кода

После знакомства с отладкой кода при возникновении ошибки работать с пошаговой отладкой будет проще.

Что такое вообще пошаговая отладка?

Это просмотр этапов выполнения кода строка за строкой.

Для чего это может быть нужно?

  • Чтобы проанализировать чужой код и понять более точно, что он делает изнутри, а не только увидеть результат его выполнения
  • Если вы начинающий программист и часто используете макрорекордер(записываете макросы) — то пошаговая отладка поможет понять какое действия выполняет каждая строка. Это поможет быстрее научиться понимать код и убирать из него лишнее, а так же совмещать различные коды
  • Если внутри кода есть ошибка логики выполнения. Это, пожалуй, самая сложная ошибка, т.к. в этом случае VBA не останавливает работу и не говорит об ошибке. Код выполняется без ошибок, но результат не такой, как ожидалось. Это означает, что либо какой-то переменной назначается не то значение, либо какое-то условие неверно или выполняется не в тот момент, в который должно. В общем по сути это ошибка разработчика, не приводящая к ошибкам синтаксиса или типов, которые VBA может отследить.

Как делать пошаговую отладку? Все просто: устанавливаете курсор в любом месте внутри кода и нажимаете клавишу F8 (либо выбрать в меню DegubStep Into). Теперь при каждом нажатии клавиши F8 код будет выполнять одну строку кода за другой в той очередности, в которой они расположены в процедуре. Если внутри процедуры будет вызов второй процедуры или функции – код пошагово выполнит и её и затем вернется в основную процедуру.
Так же хочу привести еще пару сочетаний клавиш, которые удобно применять при пошаговой отладке:

  • Shift+F8(DegubStep Over) — выполнение вложенной функции/процедуры без захода в неё. Если внутри основной процедуры или функции выполняется другая процедура или функция и Вы уверены, что она работает правильно — просматривать пошагово весь код вложенной процедуры/функции не имеет смысла. Чтобы вложенная процедура/функция выполнилась без пошагового просмотра надо просто нажать указанное сочетание клавиш тогда, когда строка вызова вложенной процедуры/функции будет подсвечена желтым
  • Ctrl+Shift+F8(DegubStep Out) — завершение вложенной функции/процедуры и выход в основную с остановкой. Если все же перестарались и перешли в пошаговый проход вложенной функции(или сделали это специально, но посмотрели все, что надо) — то нажимаете это сочетание и код быстро выполнить вложенную функцию, перейдет в основную и остановится для дальнейшей пошаговой отладки
  • Ctrl+F8(DegubRun to Cursor) — выполнение процедуры до строки, в которой на данный момент установлен курсор

Точки останова
Но куда чаще бывает нужно не просто весь код пройти пошагово, а начать пошаговое выполнение только начиная с какой-либо одной строки, чтобы не мотать строк 40 кода(да еще с циклами) ради достижения одной какой-то строки. Еще точки останова очень полезны при отладке событийных процедур(вроде Worksheet_Change, Worksheet_BeforeDoubleClick, событий элементов форм и т.п.), т.к. они в большинстве своем содержат аргументы и выполнить по F8 их просто невозможно и выполняются они только при наступлении самого события, которые они призваны обработать. Тоже самое справедливо для функций пользователя(UDF) именно для проверки их работы из листа, т.к. эти функции нельзя начать выполнять по F5 — они начинают выполняться только после их пересчета и зачастую ошибки можно выявить исключительно при вызове именно с листа.
Чтобы дать понять VBA на какой строке необходимо будет остановится необходимо установить курсор мыши в любое место нужной строки и нажать F9 или DebugToggle Breakpoint. Строка будет выделена темно-красным цветом.
Это еще называется установкой точки останова. Убрать точку останова можно так же, как она была установлена – F9 или DebugToggle Breakpoint. Так же точку основа можно установить с помощью мыши: для этого необходимо в области левее окна с кодом напротив нужной строки один раз щелкнуть левой кнопкой мыши:
Точка останова

Теперь можно запустить код любым удобным способом (в отладке это как правило делается клавишей F5 или с панели: RunRun Sub/UserForm). Как только код дойдет до указанной точки останова он остановится и строка будет подсвечена желтым. Дальше можно либо продолжить выполнение в пошаговом режиме(нажимая F8), либо(проверив значения нужных переменных и объектов) нажать опять F5 и код продолжит выполняться автоматически, пока не выполнится или не достигнет другой точки останова. Самих же точек останова может быть сколько угодно и расположены они могут быть в любой процедуре или функции.
Следует помнить, что после закрытия файла с кодом точки останова не сохраняются и при следующем открытии книги их необходимо будет установить заново, если это необходимо.


Ошибок нет, но код все равно не выполняется

Еще хочу добавить, что ошибки могут появляться не всегда, даже если они есть. Бывает и так, что код выполняется без ошибок, но однако либо выполняется не так, либо вообще ничего не делает. Как правило причин две:

  1. Логика кода построена неверно и ошибок VBA действительно не возникает. Но т.к. логика неверна — код выполняет не то, что от него ожидается. Решение одно — пошагово выполнить весь код и детально просмотреть всё, чтобы обнаружить в какой строке или строках нарушена логика
  2. Один из очень распространенных вариантов: в начале кода стоит обработчик ошибок On Error Resume Next и дальше обработчик не отменяется. Данный обработчик указывает VBA, что при возникновении ошибки её следует игнорировать и переходит к выполнению следующего оператора/строки. Таким образом ошибка хоть и возникает, но она пропускается и не показывается, а выполнение кода продолжается как ни в чем не бывало. Однако как правило одна ошибка влечет другую и третью и т.д. и может получиться так, что все строки после первой ошибочной станут так же ошибочными и как следствие не выполнятся. Данный оператор будет применяться либо до конца процедуры, либо до тех пор, пока в коде не будет поставлен иной обработчик ошибок:
    On Error GoTo Метка — переход выполнения кода к указанной метке(Метка).
    On Error GoTo 0 — по сути отменяет условный переход при возникновении ошибок. Метка 0 считается обнулением переходов

Один из примеров того, для чего может применяться обработчик ошибок можно найти в статье: Как из Excel обратиться к другому приложению. Там данный обработчик необходим, чтобы проверить открыто ли уже приложение Word. Если открыто — то ошибка не возникнет. Если же закрыто — то будет ошибка. И этот момент как правило и отслеживается. Я расставил подробные комментарии в коде, чтобы было более понятно что к чему:

Sub Check_OpenWord()
    Dim objWrdApp As Object
    On Error Resume Next 'необходимо, чтобы на первой же строке код не выдал ошибку при закрытом Word
    'пытаемся подключится к объекту Word
    Set objWrdApp = GetObject(, "Word.Application")
    'если Word закрыт - обязательно возникнет ошибка 429, 
    'указывающая на то, что невозможно подключиться к объекту Word
    'при этом переменная objWrdApp будет равняться Nothing, т.к. значение не удалось присвоить
    If objWrdApp Is Nothing Then
    'так же можно использовать и такую строку:
    'If Err.Number = 429 Then 'если ошибка 429 - значит Word не запущен - надо создавать новый
        'создаем новый экземпляр
        Set objWrdApp = CreateObject("Word.Application")
        'делаем приложение видимым. По умолчанию открывается в скрытом режиме
        objWrdApp.Visible = True
    Else
        'приложение открыто - выдаем сообщение
        MsgBox "Приложение Word уже открыто", vbInformation, "Check_OpenWord"
    End If
End Sub

Для чего вообще это нужно? Ведь можно создавать новый экземпляр. А дело в том, что не всегда правильно создавать новый — куда правильнее зачастую подключиться к ранее открытому, чем плодить новые экземпляры и захламлять диспетчер задач.
Тему обработки ошибок я здесь пока не раскрываю полностью, т.к. это не на один абзац. В одной из следующий статей постараюсь более подробно рассказать как и где их лучше применять и как правильно, а когда лучше вообще воздержаться от их использования.


Конечно, статья не описывает способы устранения ошибок — это просто невозможно. Только известных типов ошибок в VBA более 3 тысяч. Все их упоминать бессмысленно. Целью статьи было помочь начинающим найти строку с ошибкой и рассказать как производить отладку кода при необходимости. А все остальное придет с опытом. Однако на всякий случай я решил выложить файл Excel с описанием большей части ошибок, которые могут возникнуть. В файле указан номер ошибки, описание на английском и описание на русском. Причин ошибки может быть множество, поэтому нет однозначных рекомендаций по устранению каждой из них. Все зависит от данных и от самого кода.

  Ошибки VBA с описанием (152,0 KiB, 5 433 скачиваний)

Удачи в программировании!


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

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

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

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

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