На чтение 8 мин. Просмотров 30.3k.
Содержание
- Объяснение Type Mismatch Error
- Использование отладчика
- Присвоение строки числу
- Недействительная дата
- Ошибка ячейки
- Неверные данные ячейки
- Имя модуля
- Различные типы объектов
- Коллекция Sheets
- Массивы и диапазоны
- Заключение
Объяснение Type Mismatch Error
Type Mismatch Error VBA возникает при попытке назначить значение между двумя различными типами переменных.
Ошибка отображается как:
run-time error 13 – Type mismatch
Например, если вы пытаетесь поместить текст в целочисленную переменную 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.
- Запустите код, чтобы появилась ошибка.
- Нажмите Debug в диалоговом окне ошибки. Это выделит строку с ошибкой.
- Выберите View-> Watch из меню, если окно просмотра не видно.
- Выделите переменную слева от equals и перетащите ее в окно Watch.
- Выделите все справа от равных и перетащите его в окно 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 — это когда вы читаете из ячейки с ошибкой, например:
Если вы попытаетесь прочитать из этой ячейки, вы получите 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 в коде.
Если мы прочитаем эти данные в числовую переменную, то получим
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 у нас также есть объекты, которые являются более сложными. Примерами являются объекты 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. Есть очень тонкая разница.
- Worksheets — сборник рабочих листов в Workbook
- Sheets — сборник рабочих листов и диаграммных листов в Workbook
Лист диаграммы создается, когда вы перемещаете диаграмму на собственный лист, щелкая правой кнопкой мыши на диаграмме и выбирая «Переместить».
Если вы читаете коллекцию 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. Если у вас есть ошибка несоответствия, которая не раскрыта, пожалуйста, дайте мне знать в комментариях.
I am receiving «Run time error 13» when i try to submit the user form.
dTotal1 = CDbl(sval1) + CDbl(sval2) + CDbl(sval3) + CDbl(sval4) + CDbl(sval6)
Here is the complete code. Please help.
Private Sub AddTextBox()
Dim sval1 As Variant
Dim sval2 As String
Dim sval3 As String
Dim sval4 As String
Dim sval5 As String
Dim sval6 As String
Dim sval7 As String
Dim sval8 As String
Dim sval9 As String
Dim sval10 As String
Dim sval11 As String
Dim sval12 As String
Dim sval13 As String
Dim sval14 As String
Dim sval15 As String
Dim sval16 As String
Dim sval17 As String
Dim sval18 As String
Dim sval19 As String
Dim sval20 As String
Dim sval21 As String
Dim sval22 As String
Dim sval23 As String
Dim sval24 As String
Dim sval25 As String
Dim sval100 As String
Dim sval101 As String
Dim sval102 As String
Dim sval103 As String
Dim sval104 As String
Dim sval105 As String
Dim sval106 As String
Dim sval107 As String
Dim sval108 As String
Dim sval109 As String
Dim sval110 As String
Dim sval111 As String
Dim sval112 As String
Dim sval113 As String
Dim sval114 As String
Dim sval115 As String
Dim sval116 As String
Dim sval117 As String
Dim sval31 As String
Dim sval32 As String
Dim sval33 As String
Dim sval34 As String
Dim sval35 As String
Dim sval36 As String
Dim sval37 As String
Dim sval38 As String
Dim sval39 As String
Dim sval40 As String
Dim sval41 As String
Dim sval42 As String
Dim sval43 As String
Dim sval44 As String
Dim sval45 As String
Dim sval46 As String
Dim sval47 As String
Dim sval48 As String
Dim dTotal1 As String
Dim dTotal2 As String
Dim dTotal3 As String
Dim dTotal4 As String
Dim dTotal5 As String
Dim dTotal6 As String
Dim dTotal11 As String
Dim dTotal12 As String
Dim dTotal13 As String
Dim dTotal14 As String
Dim dTotal15 As String
Dim dTotal16 As String
Dim dTotal17 As String
With Me
sval1 = .CB1.Value
sval2 = .CB2.Value
sval3 = .CB3.Value
sval4 = .CB4.Value
sval6 = .CB6.Value
sval100 = .CB1.Value
sval101 = .CB2.Value
sval102 = .CB3.Value
sval103 = .CB4.Value
sval104 = .CB6.Value
sval31 = .CB1.Value
sval32 = .CB2.Value
sval33 = .CB3.Value
sval34 = .CB4.Value
sval35 = .CB6.Value
sval7 = .CB7.Value
sval8 = .CB8.Value
sval9 = .CB9.Value
sval10 = .CB10.Value
sval105 = .CB7.Value
sval106 = .CB8.Value
sval107 = .CB9.Value
sval108 = .CB10.Value
sval36 = .CB7.Value
sval37 = .CB8.Value
sval38 = .CB9.Value
sval39 = .CB10.Value
sval11 = .CB11.Value
sval12 = .CB12.Value
sval13 = .CB13.Value
sval14 = .CB14.Value
sval109 = .CB11.Value
sval110 = .CB12.Value
sval111 = .CB13.Value
sval112 = .CB14.Value
sval40 = .CB11.Value
sval41 = .CB12.Value
sval42 = .CB13.Value
sval43 = .CB14.Value
sval15 = .CB15.Value
sval16 = .CB16.Value
sval17 = .CB17.Value
sval113 = .CB15.Value
sval114 = .CB16.Value
sval115 = .CB17.Value
sval44 = .CB15.Value
sval45 = .CB16.Value
sval46 = .CB17.Value
sval18 = .CB18.Value
sval19 = .CB19.Value
sval116 = .CB18.Value
sval117 = .CB19.Value
sval47 = .CB18.Value
sval48 = .CB19.Value
If sval1 = "" Or sval1 = "NA" Then sval1 = 0
If sval2 = "" Or sval2 = "NA" Then sval2 = 0
If sval3 = "" Or sval3 = "NA" Then sval3 = 0
If sval4 = "" Or sval4 = "NA" Then sval4 = 0
If sval6 = "" Or sval6 = "NA" Then sval6 = 0
If sval100 = "NA" Then sval100 = 0 Else sval100 = 5
If sval101 = "NA" Then sval101 = 0 Else sval101 = 3
If sval102 = "NA" Then sval102 = 0 Else sval102 = 3
If sval103 = "NA" Then sval103 = 0 Else sval103 = 4
If sval104 = "NA" Then sval104 = 0 Else sval104 = 5
If sval7 = "" Or sval7 = "NA" Then sval7 = 0
If sval8 = "" Or sval8 = "NA" Then sval8 = 0
If sval9 = "" Or sval9 = "NA" Then sval9 = 0
If sval10 = "" Or sval10 = "NA" Then sval10 = 0
If sval105 = "NA" Then sval105 = 0 Else sval105 = 7
If sval106 = "NA" Then sval106 = 0 Else sval106 = 3
If sval107 = "NA" Then sval107 = 0 Else sval107 = 2
If sval108 = "NA" Then sval108 = 0 Else sval108 = 2
If sval11 = "" Or sval11 = "NA" Then sval11 = 0
If sval12 = "" Or sval12 = "NA" Then sval12 = 0
If sval13 = "" Or sval13 = "NA" Then sval13 = 0
If sval14 = "" Or sval14 = "NA" Then sval14 = 0
If sval109 = "NA" Then sval109 = 0 Else sval109 = 5
If sval110 = "NA" Then sval110 = 0 Else sval110 = 3
If sval111 = "NA" Then sval111 = 0 Else sval111 = 8
If sval112 = "NA" Then sval112 = 0 Else sval112 = 10
If sval15 = "" Or sval15 = "NA" Then sval15 = 0
If sval16 = "" Or sval16 = "NA" Then sval16 = 0
If sval17 = "" Or sval17 = "NA" Then sval17 = 0
If sval113 = "NA" Then sval113 = 0 Else sval113 = 8
If sval114 = "NA" Then sval114 = 0 Else sval114 = 10
If sval115 = "NA" Then sval115 = 0 Else sval115 = 10
If sval18 = "" Or sval18 = "NA" Then sval18 = 0
If sval19 = "" Or sval19 = "NA" Then sval19 = 0
If sval116 = "NA" Then sval116 = 0 Else sval116 = 5
If sval117 = "NA" Then sval117 = 0 Else sval117 = 7
dTotal11 = CDbl(sval100) + CDbl(sval101) + CDbl(sval102) + CDbl(sval103) + CDbl(sval104)
dTotal12 = CDbl(sval105) + CDbl(sval106) + CDbl(sval107) + CDbl(sval108)
dTotal13 = CDbl(sval109) + CDbl(sval110) + CDbl(sval111) + CDbl(sval112)
dTotal14 = CDbl(sval113) + CDbl(sval114) + CDbl(sval115)
dTotal15 = CDbl(sval116) + CDbl(sval117)
dTotal1 = CDbl(sval1) + CDbl(sval2) + CDbl(sval3) + CDbl(sval4) + CDbl(sval6)
dTotal2 = CDbl(sval7) + CDbl(sval8) + CDbl(sval9) + CDbl(sval10)
dTotal3 = CDbl(sval11) + CDbl(sval12) + CDbl(sval13) + CDbl(sval14)
dTotal4 = CDbl(sval15) + CDbl(sval16) + CDbl(sval17)
dTotal5 = CDbl(sval18) + CDbl(sval19)
.TextBox1 = Format(dTotal1, "0")
.TextBox8 = Format(dTotal11, "0")
.TextBox2 = Format(dTotal2, "0")
.TextBox9 = Format(dTotal12, "0")
.TextBox3 = Format(dTotal3, "0")
.TextBox10 = Format(dTotal13, "0")
.TextBox4 = Format(dTotal4, "0")
.TextBox11 = Format(dTotal14, "0")
.TextBox5 = Format(dTotal5, "0")
.TextBox12 = Format(dTotal15, "0")
End With
With Me
If dTotal1 = "" Then dTotal1 = 0
If dTotal2 = "" Then dTotal2 = 0
If dTotal3 = "" Then dTotal3 = 0
If dTotal4 = "" Then dTotal4 = 0
If dTotal5 = "" Then dTotal5 = 0
If dTotal11 = "" Then dTotal11 = 0
If dTotal12 = "" Then dTotal12 = 0
If dTotal13 = "" Then dTotal13 = 0
If dTotal14 = "" Then dTotal14 = 0
If dTotal15 = "" Then dTotal15 = 0
dTotal6 = CDbl(dTotal1) + CDbl(dTotal2) + CDbl(dTotal3) + CDbl(dTotal4) + CDbl(dTotal5)
dTotal16 = CDbl(dTotal11) + CDbl(dTotal12) + CDbl(dTotal13) + CDbl(dTotal14) + CDbl(dTotal15)
.TextBox6 = Format((dTotal6 / dTotal16), "Percent")
End With
End Sub
lfrandom
1,0132 gold badges10 silver badges32 bronze badges
asked Jul 30, 2013 at 13:38
1
This code is a big mess… You could use arrays, but, more important then that, you should care about types!
Anyway, your problem should be CDbl(...)
applied on a empty string.
EDIT: Improvement suggestions
- Declare your numeric variables as
Double
, instead ofString
- Replace your block
svalX = .CBX.Value
andIf svalX="" Then svalX=## Else svalX=##
withIf IsNumeric(.CB#.Value) Then sval#=.CB#.Value Else sval#=#
- You may use your
dTotal#=CDbl(sval#)+...
, butCDbl
will not be needed anymore.
answered Jul 30, 2013 at 13:56
LS_ᴅᴇᴠLS_ᴅᴇᴠ
10.8k1 gold badge23 silver badges46 bronze badges
3
You could probably fix it by replacing all CDbl() calls with Val(), but that won’t really solve the underlying problem.
As LS_Dev said: mind your data types. Try to avoid the use of Variants and don’t store numeric values in string variables to use them as numeric again a bit further on.
Anyway, you’re probably calling CDbl on a string that contains something that’s not a number.
You’re trying to avoid that higher up, but you must be missing something.
Are all «NA» really written in upper case, for example? No other special cases besides empty strings and «NA»?
answered Jul 30, 2013 at 14:09
Luc VdVLuc VdV
1,0989 silver badges14 bronze badges
1
Gagarin13 Пользователь Сообщений: 201 |
#1 20.08.2018 00:08:55
Здравствуйте уважаемые форумчане, такая проблема: вылазит в некоторых макросах такая ошибка:Run-time error «13» type mismatch Пытался гуглить, на других форумах нашел не внятные ответы, которые мне не помогли. Она то есть, то ее нету. Раз через раз появляется, сейчас вообще вылазит каждый раз даже после перезапуска файла. И срабатывает сейчас на одном макросе, хотя в этом же файле есть еще несколько похожих макросов и даже точно таких же но работают на другие листы.. но с ними все нормально. Ошибку показывает в этой строке:
Что именно ему тут не нравиться, не понимаю) |
||||
vikttur Пользователь Сообщений: 47199 |
#2 20.08.2018 00:11:22
Ну да. Подсунули программе неправильные данные — есть ошибка. Дали корректные — нет ошибки. Все? |
||
Gagarin13 Пользователь Сообщений: 201 |
#3 20.08.2018 09:24:55
Да но данные всегда одинаковы, это текст да цифры и пустых строк никогда не бывает, но тем не менее иногда ошибка вылазит. ivanok_v2,как можно исправить? vikttur, Спасибо, извиняюсь если глупые вопросы, с макросами я слабо)
У меня нету подсказок, не знаю почему Изменено: Gagarin13 — 20.08.2018 11:21:07 |
||||
ivanok_v2 Пользователь Сообщений: 712 |
#4 20.08.2018 10:04:47
этот код не всегда нормально срабатывает
тоесть, масив пустой или не двухмерный
|
||||||
Gagarin13 Пользователь Сообщений: 201 |
.. Изменено: Gagarin13 — 20.08.2018 11:21:13 |
vikttur Пользователь Сообщений: 47199 |
Загоняйте в массив два столбца, добавьте с помощью ReDim второй столбец, уберите единицу — UBound(avArr). Вариантов много… |
Gagarin13 Пользователь Сообщений: 201 |
… Изменено: Gagarin13 — 20.08.2018 11:21:17 |
Gagarin13 Пользователь Сообщений: 201 |
#8 20.08.2018 10:46:20
Изменено: Gagarin13 — 20.08.2018 11:20:10 |
||
vikttur Пользователь Сообщений: 47199 |
#9 20.08.2018 10:50:00 Gagarin13, я Вам поставлю ограничение на создание сообщений — не более 3 в день! Сколько можно просить?! Не создавайте сообщения через несколько миут. Можно вернуться и изменить предыдущее.
а с поиском по необъятному И-нету? Получили подсказку — поискали самостоятельно. Разжевывать на форуме справку по ReDim? |
||
ivanok_v2 Пользователь Сообщений: 712 |
#10 20.08.2018 10:50:50
В чем сложность? массив создать? или проверить, что переменная есть массив? |
||
I receive Runtime Error ’13’: Type Mismatch when I try to run the code. Debug highlights the ‘IF’ and ‘ElseIF’ statements, but I can’t figure out where the mistake is. Any help would be appreciated. Thanks
Dim lColumn As Long
lColumn = ws.Cells(2, Columns.Count).End(xlToLeft).Column
Dim rgMonth As Range
Dim rgTaxExp As Range
Dim i As Long, j As Long
Set rgTaxExp = Range(Cells(lRow, 10), Cells(lRow, lColumn))
Set rgMonth = Range(Cells(2, 10), Cells(2, lColumn))
For i = 1 To rgMonth.Rows.Count
For j = 1 To rgMonth.Columns.Count
If Month(date2) >= Month(rgMonth.Cells(i, j).Value) Then 'Runtime Error '13':_
Type Mismatch
Cells(lRow, 9).Copy rgTaxExp.Cells(i, j)
ElseIf Month(date2) < Month(rgMonth.Cells(i, j).Value) Then 'Runtime Error '13':_
Type Mismatch
rgTaxExp.Cells(i, j) = 0
asked Jun 28, 2013 at 15:18
5
As the error message states, either Month(date2)
or Month(rgMonth.Cells(i, j).Value)
is failing at some point in your loop.
Insert two debug statements before the If statement that is causing the error:
For j = 1 To rgMonth.Columns.Count
Debug.Print "date2 is " & date2
Debug.Print "rgMonth.Cells(i, j).Value is " & rgMonth.Cells(i, j).Value
If Month(date2) >= Month(rgMonth.Cells(i, j).Value) Then 'Runtime Error '13':_
Type Mismatch
Run your code. When you get to the error, debug and take a look at the Immediate window. The last 2 lines should show you why the error is occurring.
If you don’t see the Immediate window, you can open it by selecting View —> Immediate Window from within the Visual Basic Editor.
answered Jun 28, 2013 at 21:08
Jon CrowellJon Crowell
21.7k14 gold badges89 silver badges110 bronze badges
Summary:
This post is written with the main prospective of providing you all with ample amount of detail regarding Excel runtime error 13. So go through this complete guide to know how to fix runtime error 13 type mismatch.
In our earlier blogs, we have described the commonly found Excel file runtime error 1004, 32809 and 57121. Today in this article we are describing another Excel file runtime error 13.
Run-time error ‘13’: Type Mismatch usually occurs meanwhile the code is executed in Excel. As a result of this, you may get terminated every time from all the ongoing activities on your Excel application.
This run time error 13 also put an adverse effect on XLS/XLSX files. So before this Excel Type Mismatch error damages your Excel files, fix it out immediately with the given fixes.
Apart from that, there are many reasons behind getting the Excel file runtime error 13 when the Excel file gets corrupted this starts showing runtime error.
To recover lost Excel data, we recommend this tool:
This software will prevent Excel workbook data such as BI data, financial reports & other analytical information from corruption and data loss. With this software you can rebuild corrupt Excel files and restore every single visual representation & dataset to its original, intact state in 3 easy steps:
- Download Excel File Repair Tool rated Excellent by Softpedia, Softonic & CNET.
- Select the corrupt Excel file (XLS, XLSX) & click Repair to initiate the repair process.
- Preview the repaired files and click Save File to save the files at desired location.
Error Detail:
Error code: Run-time error ‘13’
Declaration: Excel Type Mismatch error
Here is the screenshot of this error:
Why Am I Getting Excel Runtime Error 13 Type Mismatch?
Following are some reasons for run time error 13 type mismatch:
- When multiple methods or files require to starts a program that uses Visual Basic (VB) environment
- Runtime error 13 often occurs when mismatches occur within the software applications which you require to use.
- Due to virus and malware infection as this corrupts the Windows system files or Excel-related files.
- When you tap on the function or macro present on the menu which is created by another Macro then also you will receive the same run time error 13.
- The runtime error commonly occurs due to the conflict between the software and the operating system.
- Due to the corrupt or incomplete installation of Microsoft Excel software.
- The Run-time Error 13 appears when the users try to run VBA code that includes data types that are not matched correctly. Thus it starts displaying Runtime error 13 type mismatch.
- Due to conflict with other programs while opening the VBA Excel file.
Well, these are some of the common reasons for getting the Excel file runtime error 13.
How To Fix Excel Runtime Error 13 Type Mismatch?
Learn how to Fix Excel Runtime Error 13 Type Mismatch.
1: Using Open and Repair Utility
2. Uninstall The Program
3. Scan For Virus/Malware
4. Recover Missing Macros
5. Run The ‘Regedit’ Command In CMD
6: Create New Disk Partition And Reinstall Windows
7: Use MS Excel Repair Tool
1: Using Open and Repair Utility
There is a ‘File Recovery’ mode within Excel which gets activated automatically when any corruption issue hits your worksheet or workbook.
But in some cases, Excel won’t offer this ‘File Recovery’ mode and at that time you need to use Excel inbuilt tool ‘Open and Repair’.
Using this inbuilt utility tool you can recover corrupted/damaged Excel files. Try the following steps to fix Visual Basic runtime error 13 type mismatch in Excel.
Here follow the steps to do so:
- In the File menu> click “Open”
- And select corrupt Excel file > from the drop-down list of open tab > select “Open and Repair”
- Lastly, click on the “Repair” button.
However, it is found that the inbuilt repair utility fails to repair the severely damaged Excel file.
2. Uninstall The Program
It is found some application and software causes the runtime error.
So, to fix the Excel file error, simply uninstall the problematic apps and programs.
- First, go to the Task Manager and stop the running programs.
- Then in the start menu > select Control Panel.
- In the Control Panel > choose Add or Remove Program.
- Here, you will get the list of installed programs on your PC.
- Then from the list select Microsoft Work.
- Click on uninstall to remove it from the PC.
Hope doing this will fix the Excel file Runtime error 13, but if not then follow the third solution.
3. Scan For Virus/Malware
Virus intrusion is quite a big problem for all Windows users, as it causes several issues for PC and Excel files.
This can be the great reason behind this Runtime 13 error. As viruses damage the core program file of MS Office which is important for the execution of Excel application.
This makes the file unreadable and starts generating the following error message: Visual Basic runtime error 13 type mismatch in Excel
To avoid this error, you need to remove all virus infections from your system using the reliable anti-virus removal tool.
Well, it is found that if your Windows operating system in having viruses and malware then this might corrupt Excel file and as a result, you start facing the runtime file error 13.
So, it is recommended to scan your system with the best antivirus program and make your system malware-free. Ultimately this will also fix runtime error 13.
4. Recover Missing Macros
Well, as it is found that users are getting the runtime error 13 due to the missing macros, So try to recover the missing Macros.
Here follow the steps to do so:
- Open the new Excel file > and set the calculation mode to Manual
- Now from the Tools menu select Macro > select Security > High option.
- If you are using Excel 2007, then click the Office button > Excel Options > Trust Center in the left panel
- And click on Trust Center Settings button > Macro Settings > Disable All Macros without Notification in the Macro Settings section > click OK twice.
- Now, open the corrupted workbook. If Excel opens the workbook a message appears that the macros are disabled.
- But if in case Excel shut down, then this method is not workable.
- Next press [Alt] + [F11] for opening the Visual Basic Editor (VBE).
- Make use of the Project Explorer (press [Ctrl]+R) > right-click a module > Export File.
- Type name and folder for the module > and repeat this step as many times as required to export the entire module.
- Finally, close the VBE and exit.
Now open the new blank workbook (or the recently constructed workbook that contains recovered data from the corrupted workbook) and import the modules.
5. Run The ‘Regedit’ Command In CMD
This Excel error 13 can also be fixed by running the ‘Regedit’ command in the command prompt.
- In the search menu of your system’s start menu type run command.
- Now in the opened run dialog box type “regedit” command. After that hit the OK
- This will open the registry editor. On its right side there is a ‘LoadApplnit_DLLs value.’ option, just make double-tap to it.
- Change the value from 1 to ‘0‘and then press the OK.
- Now take exit from this opened registry editor.
- After completing all this, restart your PC.
Making the above changes will definitely resolve the Runtime Error 13 Type Mismatch.
6: Create New Disk Partition And Reinstall Windows
If even after trying all the above-given fixes Excel type mismatched error still persists. In that case, the last option left here is to create the new partition and reinstall Windows.
- In your PC insert windows DVD/CD and after that begin the installation procedure.
- For installation, choose the language preference.
- Tap to the option” I accept” and then hit the NEXT
- Select the custom advance option and then choose the Disk O partition 1
- Now hit the delete> OK button.
- The same thing you have to repeat after selecting the Disk O partition 2.
- Now hit the delete> OK button to delete this too.
- After completing the deletion procedure, tap to create a new partition.
- Assign the disk size and tap to the Apply.
- Now choose the Disk 0 partition 2 and then hit the Formatting.
- After complete formatting, hit the NEXT button to continue.
Note: before attempting this procedure don’t forget to keep a complete backup of all your data.
However, if you are still facing the Excel Runtime file error 13 then make use of the third party automatic repair tool.
7: Use MS Excel Repair Tool
It is recommended to make use of the MS Excel Repair Tool. This is the best tool to repair all sort of issues, corruption, errors in Excel workbooks. This tool allows to easily restore all corrupt excel file including the charts, worksheet properties cell comments, and other important data.
* Free version of the product only previews recoverable data.
This is a unique tool to repair multiple excel files at one repair cycle and recovers the entire data in a preferred location. It is easy to use and compatible with both Windows as well as Mac operating systems.
Steps to Utilize MS Excel Repair Tool:
excel-repair-main-interface-1
stellar-repair-for-excel-select-file-2
stellar-repair-for-excel-repairing-3
stellar-repair-for-excel-preview-4
stellar-repair-for-excel-save-5
stellar-repair-for-excel-saving-6
stellar-repair-for-excel-repaired-7
Final Verdict:
After reading the complete post you must have got enough idea on Visual Basic runtime error 13 type mismatch in Excel. Following the listed given fixes you are able to fix the Excel runtime file error 13.
I tried my best to provide ample information about the runtime error and possible workarounds that will help you to fix the Excel file error.
So, just make use of the solutions given and check whether the Excel error is fixed or not.
In case you have any additional workarounds that proved successful or questions concerning the ones presented, do tell us in the comments.
Hope you find this post informative and helpful.
Thanks for reading…!
Priyanka is a content marketing expert. She writes tech blogs and has expertise in MS Office, Excel, and other tech subjects. Her distinctive art of presenting tech information in the easy-to-understand language is very impressive. When not writing, she loves unplanned travels.