Type mismatch vba word ошибка

I have the following code as part of my sub trying to assign a range:

'Set xlApp = CreateObject("Excel.Application")

Dim xlApp As Object
Set xlApp = GetObject(, "Excel.Application")
xlApp.Visible = False
xlApp.ScreenUpdating = False

Dim CRsFile As String
Dim CRsMaxRow As Integer

' get the CR list
CRsFile = "CRs.xls"
Set CRsWB = xlApp.Workbooks.Open("C:\Docs\" + CRsFile)
With CRsWB.Worksheets("Sheet1")
  .Activate
  CRsMaxRow = .Range("A1").CurrentRegion.Rows.Count

  Set CRs = .Range("A2:M" & CRsMaxRow)

End With

Dim interestingFiles As Range

' get the files names that we consider interesting to track
Set FilesWB = xlApp.Workbooks.Open("files.xlsx")
With FilesWB.Worksheets("files")
    .Activate
    Set interestingFiles = .Range("A2:E5")
End With

Do you have any idea why am I getting a run time type mismatch error?

Community's user avatar

asked May 5, 2013 at 12:51

banjo's user avatar

If you run the code from Word then the problem is in the declaration of ‘interestingFiles’ variable. Range exist in Word as well so use either Variant or add reference to Excel and then use Excel.Range.

Without Excel reference:

Dim interestingFiles As Variant

And with Excel reference:

Dim interestingFiles As Excel.Range

answered May 5, 2013 at 16:04

Daniel Dušek's user avatar

Daniel DušekDaniel Dušek

13.7k5 gold badges36 silver badges51 bronze badges

2

Kindly set xlApp object as in below code.
Also you provide complete path for your workbook when opening it.

Sub test()
        Dim interestingFiles As Range
        Dim xlApp As Object

        Set xlApp = GetObject(, "Excel.Application")
        ' get the files names

        Dim path As String
        path = "C:\Users\Santosh\Desktop\file1.xlsx"

        Set FilesWB = xlApp.Workbooks.Open(path)
        With FilesWB.Worksheets(1)
            .Activate
            Set interestingFiles = .Range("A2:E5")
        End With

    End Sub

answered May 5, 2013 at 13:00

Santosh's user avatar

SantoshSantosh

12.2k4 gold badges41 silver badges73 bronze badges

10

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

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

Содержание

  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

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

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

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

1

2

3

4

5

6

7

8

9

Sub TypeMismatchStroka()

    ‘ Объявите переменную типа long integer

    Dim total As Long

    ‘ Назначение строки приведет к Type Mismatch Error

    total = «Иван»

End Sub

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

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

1

2

3

4

5

6

7

8

9

Sub TypeMismatchData()

    ‘ Объявите переменную типа Date

    Dim ReportDate As Date

    ‘ Назначение числа вызывает Type Mismatch Error

    ReportDate = «21-22»

End Sub

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

1

2

3

4

5

6

7

Dim x As Long

‘ VBA преобразует в целое число 100

x = 99.66

‘ VBA преобразует в целое число 66

x = «66»

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

1

2

3

4

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

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

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

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

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

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

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

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 — это когда вы читаете из ячейки с ошибкой, например:

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

1

2

3

4

Dim sText As String

‘ Type Mismatch Error, если ячейка содержит ошибку

sText = Sheet1.Range(«A1»).Value

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

1

2

3

4

Dim sText As String

If IsError(Sheet1.Range(«A1»).Value) = False Then

    sText = Sheet1.Range(«A1»).Value

End If

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

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

1

2

3

4

5

6

Function CheckForErrors(rg As Range) As Long

    On Error Resume Next

    CheckForErrors = rg.SpecialCells(xlCellTypeFormulas, xlErrors).Count

End Function

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

1

2

3

4

5

6

7

8

9

10

Sub DoStuff()

    If CheckForErrors(Sheet1.Range(«A1:Z1000»)) > 0 Then

        MsgBox «На листе есть ошибки. Пожалуйста, исправьте и запустите макрос снова.»

        Exit Sub

    End If

    ‘ Продолжайте здесь, если нет ошибок

End Sub

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

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

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

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

1

2

3

4

5

6

7

8

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

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

1

2

3

4

5

6

7

8

Function CheckForTextCells(rg As Range) As Long

    ‘ Подсчет числовых ячеек

    If rg.Count = rg.SpecialCells(xlCellTypeConstants, xlNumbers).Count Then

        CheckForTextCells = True

    End If

End Function

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

1

2

3

4

5

6

7

8

9

10

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.

1

2

3

4

5

6

Sub IspolzovanieImeniModulya()

    ‘ Type Mismatch Error

    Debug.Print module1

End Sub

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

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

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

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

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

1

2

3

4

5

6

7

8

9

10

11

12

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», если рабочая книга содержит лист с диаграммой.

1

2

3

4

5

6

7

8

9

Sub SheetsError()

    Dim sh As Worksheet

    For Each sh In ThisWorkbook.Sheets

        Debug.Print sh.Name

    Next sh

End Sub

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

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

1

2

3

4

5

6

7

8

9

10

11

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 .

1

2

3

4

5

6

7

8

9

10

11

Sub OshibkaIspolzovanieMassiva()

    Dim arr As Variant

    ‘ Присвойте диапазон массиву

    arr = Sheet1.Range(«A1»).Value

    ‘ Здесь будет происходить Type Mismatch Error

    Debug.Print arr(1, 1)

End Sub

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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

Источник

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

puneet-gogia-excel-champs-09-06-23

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.

type-mismatch-error

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

What is VBA

  • VBA ERROR Handling
  • VBA Automation Error (Error 440)
  • VBA Error 400
  • VBA Invalid Procedure Call Or Argument Error (Error 5)
  • VBA Object Doesn’t Support this Property or Method Error (Error 438)
  • VBA Object Required Error (Error 424)
  • VBA Out of Memory Error (Error 7)
  • VBA Overflow Error (Error 6)
  • VBA Runtime Error (Error 1004)
  • VBA Subscript Out of Range Runtime Error (Error 9)

Понравилась статья? Поделить с друзьями:
  • Type mismatch vba excel ошибка массив
  • Type mismatch vba excel ошибка runtime 13
  • Type mismatch in expression access ошибка
  • Txd workshop ошибка list index out of bounds
  • Ts vms ошибка подключения что делать