Vba excel range type mismatch

I’m getting a type mismatch error while comparing a range value to "" or vbNullString. i read many similar q+a posts that deal with this issue.

The data is all numbers or "".

Sub vegetableCounting()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim ws1Range As Excel.range, ws2Range As Excel.range, ws3Range As Excel.range, ws2Loop As Excel.range
Dim ws1Row As Long, ws1Col As Long, ws2Row As Long, ws2Col As Long
'
Dim rowCounter As Long, colCounter As Long, rowsMendo As Long
Dim mendoSum As Double
'
Set ws1 = Sheets("shareSchedule")
Set ws2 = Sheets("shareDistribution")
Set ws3 = Sheets("vegCount")
'***not yet set to the full ranges***
Set ws1Range = ws1.range("E7:H11") 'shareSchedule
Set ws2Range = ws2.range("D7:BB17") 'shareDistribution
Set ws3Range = ws3.range("D7:BB11") 'vegetableCount
'***not yet set to the full ranges***
rowsMendo = 0
rowCounter = 0
colCounter = 0
mendoSum = 0

For ws1Row = 0 To ws1Range.Rows.count Step 1
    For ws1Col = 0 To ws1Range.Columns.count Step 1
        If ws1Range.Offset(ws1Row, ws1Col).value <> "" Then
            For Each ws2Loop In ws2Range '11rows*51cols = 561
                ws2Row = ws2Row + rowCounter + rowsMendo
                ws2Col = ws2Col + colCounter
                If ws2Range.Offset(ws2Row, ws2Col).value = "" Then
                    Exit For
                Else
                    If ws1Range.Offset(ws1Row, ws1Col).Interior.ColorIndex = 24 And _
                    ws2Range.Offset(ws2Row, ws2Col).Interior.ColorIndex = 24 Then 'a MENDO match
                        If rowCounter < 3 Then
                            mendoSum = mendoSum + ws1Range.Offset(ws1Row, ws1Col).value * ws2Range.Offset(ws2Col, ws2Row)
                            rowCounter = rowCounter + 1
                        ElseIf rowCounter = 3 Then
                            colCounter = colCounter + 1
                            rowCounter = 0
                        ElseIf colCounter = ws2Range.Columns.count + 1 And _
                        ws2Range.Offset(ws2Row, 1).Interior.ColorIndex = 24 And _
                        ws2Range.Offset(ws2Row + 4, 1).Interior.ColorIndex = 24 Then
                            colCounter = 0
                            rowsMendo = rowsMendo + 3
                        ElseIf colCounter = ws2Range.Columns.count + 1 And _
                        ws2Range.Offset(ws2Row, 1).Interior.ColorIndex = xlNone And _
                        ws2Range.Offset(ws2Row + 4, 1).Interior.ColorIndex = xlNone Then
                            colCounter = 0
                            rowsMendo = rowsMendo + 1
                        End If

                        ws3Range.Offset(ws1Row, ws2Col) = ws1Range.Offset(ws1Row, ws1Col).value * ws2Range.Offset(ws2Row, ws2Col).value

                    End If
                End If
            Next
        End If
    Next ws1Col
Next ws1Row

'for ws2
                'Offset(0, 0), Offset(1, 0), Offset(2, 0), then
                'Offset(0, 1), Offset(1, 1), Offset(2, 1), then
                'Offset(0, 2), Offset(1, 2), Offset(2, 2), then
                'etc
End Sub

i get the error on

  If ws1Range.Offset(ws1Row, ws1Col).value <> "" Then

and ill prob get it again on

If ws2Range.Offset(ws2Row, ws2Col).value = "" Then

any thoughts? here are some images of the worksheets im trying to pull from

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

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

Содержание

  1. Why is VBA throwing type mismatch errors when passing a Range object?
  2. 2 Answers 2
  3. Разбор ошибки Type Mismatch Error
  4. Объяснение Type Mismatch Error
  5. Использование отладчика
  6. Присвоение строки числу
  7. Недействительная дата
  8. Ошибка ячейки
  9. Неверные данные ячейки
  10. Имя модуля
  11. Различные типы объектов
  12. Коллекция Sheets
  13. Массивы и диапазоны
  14. Заключение
  15. Getting «error: type mismatch» in VBA
  16. 3 Answers 3
  17. Related
  18. Hot Network Questions
  19. Subscribe to RSS
  20. Type mismatch (Error 13)
  21. Support and feedback
  22. VBA – Type Mismatch (Run-time Error 13)
  23. VBA Type Mismatch Errors
  24. What is a Type Mismatch Error?
  25. Mismatch Error Caused by Worksheet Calculation
  26. Mismatch Error Caused by Entered Cell Values
  27. Mismatch Error Caused by Calling a Function or Sub Routine Using Parameters
  28. Mismatch Error Caused by using Conversion Functions in VBA Incorrectly
  29. General Prevention of Mismatch Errors
  30. VBA Coding Made Easy
  31. Define your variables as Variant Type
  32. Use the OnError Command to Handle Errors
  33. Use the OnError Command to Supress Errors
  34. Converting the Data to a Data Type to Match the Declaration
  35. Testing Variables Within Your Code
  36. Objects and Mismatch Errors
  37. VBA Code Examples Add-in

Why is VBA throwing type mismatch errors when passing a Range object?

I have this function (which I based off a function here):

I have tried calling it like so:

And I Always Get the Error: «run-time error 13, type mismatch» once the code hits the call to Foo.

Additionally, I have tried:

Which gives the error: «Object Expected» I assume this means that parentheses deference a pointer to its value, and are not (always?) used in function/subroutine calls.

I have also tried writing the function without the «ByVal» but that failed as well.

EDIT Tried what @ScottCraner suggested but the error remains:

EDIT Important Note: this is being run from a Macro Enabled Word Document, the Excel Library is imported and the workbook is opened from the code.

2 Answers 2

When using the () you need to assign it to a variable or other direction:

You can also just use Foo rng or Call Foo(rng)

Thanks to the ever correct @Rory

But the real issue seems that you have used the word range as a variable, sub or Function elsewhere and this is superseding the correct usage of it as an object.

As was pointed out by @Mat’sMug

So the problem turned out to be that because this code was run from word, with the Excel library as a reference, the Range type defaulted to a MS-Word Range object instead of a MS-Excel Range object, meaning that my function was looking for the wrong type of parameter. Here is the corrected code (notice the explicit reference to the Excel lib when defining Foo and the Range variable r):

As @ScottCraner and others pointed out the issue could easily have been that I had a variable/function called Range defined somewhere else. In a way that is sort of what happened, only it was defined in the Word Library, not in my code.

Источник

Разбор ошибки 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. Если у вас есть ошибка несоответствия, которая не раскрыта, пожалуйста, дайте мне знать в комментариях.

Источник

Getting «error: type mismatch» in VBA

Am getting Run-time error 13 . Type Mismatch. But i cant figure out why. Any help?

When i try to use other test cells is fine, the problem is with those. but they are numbers inside «ttotal_comission» why does VBA takes it as something else?

3 Answers 3

The problem is that Rows(I) is returning a range object, not an integer value. You should fully qualify your statements like this: TotalCRng.Rows(I).Cells(1, 1).Value or possibly TotalCRng.Cells(1, 1).Value . Written as it is, Excel will return the value from Rows(I) if it happens to be a single cell, in which case the range’s value property is called, but otherwise will raise the Type Mismatch error you’re seeing because you’re attempting to compare a range to an integer.

Also, bear in mind that only the top left cell of a merged range will actually return a value.

You could use use a construct like this:

If you are trying to check the value of the cells in each row, you need to loop through the cells and compare the values individually.

If the ranges are just single columns, instead of looping through each row, you can loop through each cell for the same effect.

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.17.43323

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Type mismatch (Error 13)

Visual Basic is able to convert and coerce many values to accomplish data type assignments that weren’t possible in earlier versions.

However, this error can still occur and has the following causes and solutions:

  • Cause: The variable or property isn’t of the correct type. For example, a variable that requires an integer value can’t accept a string value unless the whole string can be recognized as an integer.

Solution: Try to make assignments only between compatible data types. For example, an Integer can always be assigned to a Long, a Single can always be assigned to a Double, and any type (except a user-defined type) can be assigned to a Variant.

  • Cause: An object was passed to a procedure that is expecting a single property or value.

Solution: Pass the appropriate single property or call a method appropriate to the object.

Cause: A module or project name was used where an expression was expected, for example:

Solution: Specify an expression that can be displayed.

Cause: You attempted to mix traditional Basic error handling with Variant values having the Error subtype (10, vbError), for example:

Solution: To regenerate an error, you must map it to an intrinsic Visual Basic or a user-defined error, and then generate that error.

Cause: A CVErr value can’t be converted to Date. For example:

Solution: Use a Select Case statement or some similar construct to map the return of CVErr to such a value.

  • Cause: At run time, this error typically indicates that a Variant used in an expression has an incorrect subtype, or a Variant containing an array appears in a Print # statement.

Solution: To print arrays, create a loop that displays each element individually.

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

Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA – Type Mismatch (Run-time Error 13)

In this Article

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:

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.

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

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

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

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

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

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.

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 5 th cell down has the text value and this has caused the code to fail

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

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

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!

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

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.

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.

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:

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:

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

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

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

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:

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:

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

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

Понравилась статья? Поделить с друзьями:
  • Vba excel range object methods
  • Vba excel range interior color
  • Vba excel range from cells
  • Vba excel range format
  • Vba excel save to my documents