Ошибка runtime error 13 type mismatch как исправить

Разбор ошибки Type Mismatch Error в подробной статье на сайте ExcelPedia. Ознакомиться со статьей с подробным разбором ошибки Type Mismatch Error в Эксель

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

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

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

Обзор «Type mismatch»

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Продукт Solvusoft

Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.

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

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

 

Gagarin13

Пользователь

Сообщений: 201
Регистрация: 21.05.2018

#1

20.08.2018 00:08:55

Код
Sub Del_Array_SubStr_Расщепление_Неточно_Соответствие()
    Dim sSubStr As String    'искомое слово или фраза
    Dim lCol As Long    'номер столбца с просматриваемыми значениями
    Dim lLastRow As Long, li As Long
    Dim avArr, lr As Long
    Dim arr

    lCol = Val(InputBox("Укажите номер столбца, в котором искать указанное значение", "Запрос параметра", 12))
    If lCol = 0 Then Exit Sub
    Application.ScreenUpdating = 0
    lLastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count
    'заносим в массив значения листа, в котором необходимо удалить строки
    arr = Cells(1, lCol).Resize(lLastRow).Value
    'Получаем с Расщепление значения, которые надо удалить в активном листе
    With Sheets("Расщепление") 'Имя листа с диапазоном значений на удаление
        avArr = .Range(.Cells(3, 14), .Cells(.Rows.Count, 14).End(xlUp))
    End With
    'удаляем
    Dim rr As Range
    For lr = 1 To UBound(avArr, 1)
        sSubStr = avArr(lr, 1)
        For li = 1 To lLastRow 'цикл с первой строки до конца
            If InStr(1, arr(li, 1), sSubStr, 1) > 0 Then
                If rr Is Nothing Then
                    Set rr = Cells(li, 12)
                Else
                    Set rr = Union(rr, Cells(li, 12))
                End If
            End If
            DoEvents
        Next li
        DoEvents
    Next lr
   If Not rr Is Nothing Then rr.Rows.Interior.Color = 65535
    Application.ScreenUpdating = 1
End Sub

Здравствуйте уважаемые форумчане, такая проблема: вылазит в некоторых макросах такая ошибка:Run-time error «13» type mismatch

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

Ошибку показывает в этой строке:

Код
For lr = 1 To UBound(avArr, 1)

Что именно ему тут не нравиться, не понимаю)
Заранее спасибо за помощь

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#2

20.08.2018 00:11:22

Цитата
Она то есть, то ее нету.

Ну да. Подсунули программе неправильные данные — есть ошибка. Дали корректные — нет ошибки.
Ошибка говорит о несоответствии типов данных. Вместо даты текст, вместо числа пустая строка «», в переменную типа Вyte пытаетесь записать число 300… Поверяйте исходные данные.
Когда высветится ошибка, нажмите Debug — Вам редактор покажет подсвеченную желтым строку. Наведите курсор на переменую, ссылку… — в подсказке увидите значение.

Все?
Как Вы тему назовете, так она и поплыват… Если нужно решение по конкретному коду — название темы должно отражать суть задачи. Предложите новое. Модераторы заменят. И файл-пример поможет.

 

Gagarin13

Пользователь

Сообщений: 201
Регистрация: 21.05.2018

#3

20.08.2018 09:24:55

Цитата
vikttur написал:
Вместо даты текст, вместо числа пустая строка «», в переменную типа Вyte пытаетесь записать число 300… Поверяйте исходные данные

Да но данные всегда одинаковы, это текст да цифры и пустых строк никогда не бывает, но тем не менее иногда ошибка вылазит.

ivanok_v2,как можно исправить?

vikttur, Спасибо, извиняюсь если глупые вопросы, с макросами я слабо)

Цитата
vikttur написал: Наведите курсор на переменую, ссылку… — в подсказке увидите значение.

У меня нету подсказок, не знаю почему

Изменено: Gagarin1320.08.2018 11:21:07

 

ivanok_v2

Пользователь

Сообщений: 712
Регистрация: 19.08.2018

#4

20.08.2018 10:04:47

Цитата
Gagarin13 написал:For lr = 1 To UBound(avArr, 1)

этот код не всегда нормально срабатывает

Код
  avArr = .Range(.Cells(3, 14), .Cells(.Rows.Count, 14).End(xlUp))

тоесть, масив пустой или не двухмерный

Код
UBound(avArr, 1)
 

Gagarin13

Пользователь

Сообщений: 201
Регистрация: 21.05.2018

..

Изменено: Gagarin1320.08.2018 11:21:13

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

Загоняйте в массив два столбца, добавьте с помощью ReDim второй столбец, уберите единицу — UBound(avArr). Вариантов много…

 

Gagarin13

Пользователь

Сообщений: 201
Регистрация: 21.05.2018

Изменено: Gagarin1320.08.2018 11:21:17

 

Gagarin13

Пользователь

Сообщений: 201
Регистрация: 21.05.2018

#8

20.08.2018 10:46:20

Цитата
.

Изменено: Gagarin1320.08.2018 11:20:10

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#9

20.08.2018 10:50:00

Gagarin13, я Вам поставлю ограничение на создание сообщений — не более 3 в день! Сколько можно просить?! Не создавайте сообщения через несколько миут. Можно вернуться и изменить предыдущее.
Вернитесь и в своих темах наведите порядок. Модераторы удалят лишнее.

Цитата
с макросами я слабо)

а с поиском по необъятному И-нету? Получили подсказку — поискали самостоятельно. Разжевывать на форуме  справку по ReDim?

 

ivanok_v2

Пользователь

Сообщений: 712
Регистрация: 19.08.2018

#10

20.08.2018 10:50:50

Цитата
Gagarin13 написал: У меня нету подсказок, не знаю почему

В чем сложность? массив создать? или проверить, что переменная есть массив?

В этой статье представлена ошибка с номером Ошибка 13, известная как Ошибка Microsoft Access 13, описанная как Несоответствие типов.

О программе Runtime Ошибка 13

Время выполнения Ошибка 13 происходит, когда Microsoft Access дает сбой или падает во время запуска, отсюда и название. Это не обязательно означает, что код был каким-то образом поврежден, просто он не сработал во время выполнения. Такая ошибка появляется на экране в виде раздражающего уведомления, если ее не устранить. Вот симптомы, причины и способы устранения проблемы.

Определения (Бета)

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

  • Доступ — НЕ ИСПОЛЬЗУЙТЕ этот тег для Microsoft Access, используйте вместо него [ms-access].
  • Несоответствие — Несоответствие относится к несоответствие или несоответствие
  • Несоответствие типа . Ошибка несоответствия типа обычно обнаруживается в контексте языков со строгой типизацией.
  • Доступ — Microsoft Access, также известный как Microsoft Office Access, представляет собой систему управления базами данных от Microsoft, которая обычно сочетает в себе реляционный Microsoft JetACE Database Engine с графическим пользовательским интерфейсом и инструментами для разработки программного обеспечения.
  • Microsoft доступ — Microsoft Access, также известный как Microsoft Office Access, представляет собой систему управления базами данных от Microsoft, которая обычно сочетает в себе реляционное ядро ​​СУБД Microsoft JetACE с графическим пользовательским интерфейсом и инструментами разработки программного обеспечения.
  • < b> Тип. Типы и системы типов используются для обеспечения уровней абстракции в программах.

Симптомы Ошибка 13 — Ошибка Microsoft Access 13

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

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

Fix Ошибка Microsoft Access 13 (Error Ошибка 13)
(Только для примера)

Причины Ошибка Microsoft Access 13 — Ошибка 13

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

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

Методы исправления

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

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

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

Метод 1 — Закройте конфликтующие программы

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

  • Откройте диспетчер задач, одновременно нажав Ctrl-Alt-Del. Это позволит вам увидеть список запущенных в данный момент программ.
  • Перейдите на вкладку «Процессы» и остановите программы одну за другой, выделив каждую программу и нажав кнопку «Завершить процесс».
  • Вам нужно будет следить за тем, будет ли сообщение об ошибке появляться каждый раз при остановке процесса.
  • Как только вы определите, какая программа вызывает ошибку, вы можете перейти к следующему этапу устранения неполадок, переустановив приложение.

Метод 2 — Обновите / переустановите конфликтующие программы

Использование панели управления

  • В Windows 7 нажмите кнопку «Пуск», затем нажмите «Панель управления», затем «Удалить программу».
  • В Windows 8 нажмите кнопку «Пуск», затем прокрутите вниз и нажмите «Дополнительные настройки», затем нажмите «Панель управления»> «Удалить программу».
  • Для Windows 10 просто введите «Панель управления» в поле поиска и щелкните результат, затем нажмите «Удалить программу».
  • В разделе «Программы и компоненты» щелкните проблемную программу и нажмите «Обновить» или «Удалить».
  • Если вы выбрали обновление, вам просто нужно будет следовать подсказке, чтобы завершить процесс, однако, если вы выбрали «Удалить», вы будете следовать подсказке, чтобы удалить, а затем повторно загрузить или использовать установочный диск приложения для переустановки. программа.

Использование других методов

  • В Windows 7 список всех установленных программ можно найти, нажав кнопку «Пуск» и наведя указатель мыши на список, отображаемый на вкладке. Вы можете увидеть в этом списке утилиту для удаления программы. Вы можете продолжить и удалить с помощью утилит, доступных на этой вкладке.
  • В Windows 10 вы можете нажать «Пуск», затем «Настройка», а затем — «Приложения».
  • Прокрутите вниз, чтобы увидеть список приложений и функций, установленных на вашем компьютере.
  • Щелкните программу, которая вызывает ошибку времени выполнения, затем вы можете удалить ее или щелкнуть Дополнительные параметры, чтобы сбросить приложение.

Метод 3 — Обновите программу защиты от вирусов или загрузите и установите последнюю версию Центра обновления Windows.

Заражение вирусом, вызывающее ошибку выполнения на вашем компьютере, необходимо немедленно предотвратить, поместить в карантин или удалить. Убедитесь, что вы обновили свою антивирусную программу и выполнили тщательное сканирование компьютера или запустите Центр обновления Windows, чтобы получить последние определения вирусов и исправить их.

Метод 4 — Переустановите библиотеки времени выполнения

Вы можете получить сообщение об ошибке из-за обновления, такого как пакет MS Visual C ++, который может быть установлен неправильно или полностью. Что вы можете сделать, так это удалить текущий пакет и установить новую копию.

  • Удалите пакет, выбрав «Программы и компоненты», найдите и выделите распространяемый пакет Microsoft Visual C ++.
  • Нажмите «Удалить» в верхней части списка и, когда это будет сделано, перезагрузите компьютер.
  • Загрузите последний распространяемый пакет от Microsoft и установите его.

Метод 5 — Запустить очистку диска

Вы также можете столкнуться с ошибкой выполнения из-за очень нехватки свободного места на вашем компьютере.

  • Вам следует подумать о резервном копировании файлов и освобождении места на жестком диске.
  • Вы также можете очистить кеш и перезагрузить компьютер.
  • Вы также можете запустить очистку диска, открыть окно проводника и щелкнуть правой кнопкой мыши по основному каталогу (обычно это C :)
  • Щелкните «Свойства», а затем — «Очистка диска».

Метод 6 — Переустановите графический драйвер

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

  • Откройте диспетчер устройств и найдите драйвер видеокарты.
  • Щелкните правой кнопкой мыши драйвер видеокарты, затем нажмите «Удалить», затем перезагрузите компьютер.

Метод 7 — Ошибка выполнения, связанная с IE

Если полученная ошибка связана с Internet Explorer, вы можете сделать следующее:

  1. Сбросьте настройки браузера.
    • В Windows 7 вы можете нажать «Пуск», перейти в «Панель управления» и нажать «Свойства обозревателя» слева. Затем вы можете перейти на вкладку «Дополнительно» и нажать кнопку «Сброс».
    • Для Windows 8 и 10 вы можете нажать «Поиск» и ввести «Свойства обозревателя», затем перейти на вкладку «Дополнительно» и нажать «Сброс».
  2. Отключить отладку скриптов и уведомления об ошибках.
    • В том же окне «Свойства обозревателя» можно перейти на вкладку «Дополнительно» и найти пункт «Отключить отладку сценария».
    • Установите флажок в переключателе.
    • Одновременно снимите флажок «Отображать уведомление о каждой ошибке сценария», затем нажмите «Применить» и «ОК», затем перезагрузите компьютер.

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

Другие языки:

How to fix Error 13 (Microsoft Access Error 13) — Type mismatch.
Wie beheben Fehler 13 (Microsoft Access-Fehler 13) — Nichtübereinstimmung des Typs.
Come fissare Errore 13 (Errore di Microsoft Access 13) — Mancata corrispondenza del tipo.
Hoe maak je Fout 13 (Microsoft Access-fout 13) — Typ komt niet overeen.
Comment réparer Erreur 13 (Erreur d’accès Microsoft 13) — Incompatibilité de type.
어떻게 고치는 지 오류 13 (마이크로소프트 액세스 오류 13) — 유형이 일치하지 않습니다.
Como corrigir o Erro 13 (Erro 13 do Microsoft Access) — Incompatibilidade de tipo.
Hur man åtgärdar Fel 13 (Microsoft Access-fel 13) — Typmatchningsfel.
Jak naprawić Błąd 13 (Błąd Microsoft Access 13) — Niezgodność typu.
Cómo arreglar Error 13 (Error 13 de Microsoft Access) — Falta de coincidencia de tipos.

The Author Об авторе: Фил Харт является участником сообщества Microsoft с 2010 года. С текущим количеством баллов более 100 000 он внес более 3000 ответов на форумах Microsoft Support и создал почти 200 новых справочных статей в Technet Wiki.

Следуйте за нами: Facebook Youtube Twitter

Рекомендуемый инструмент для ремонта:

Этот инструмент восстановления может устранить такие распространенные проблемы компьютера, как синие экраны, сбои и замораживание, отсутствующие DLL-файлы, а также устранить повреждения от вредоносных программ/вирусов и многое другое путем замены поврежденных и отсутствующих системных файлов.

ШАГ 1:

Нажмите здесь, чтобы скачать и установите средство восстановления Windows.

ШАГ 2:

Нажмите на Start Scan и позвольте ему проанализировать ваше устройство.

ШАГ 3:

Нажмите на Repair All, чтобы устранить все обнаруженные проблемы.

СКАЧАТЬ СЕЙЧАС

Совместимость

Требования

1 Ghz CPU, 512 MB RAM, 40 GB HDD
Эта загрузка предлагает неограниченное бесплатное сканирование ПК с Windows. Полное восстановление системы начинается от $19,95.

ID статьи: ACX06168RU

Применяется к: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000

Совет по увеличению скорости #20

Очистка папки предварительной выборки Windows XP:

Предварительная выборка — это полезный и уникальный метод, используемый в Windows XP. Однако со временем он может накапливать устаревшие и редко используемые ссылки, что может значительно замедлить работу вашего компьютера. Просто откройте C (системный диск): / windows / prefetch, удалите все файлы и перезагрузитесь.

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

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

Excel VBA Run-time error ’13’ Type mismatch

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

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

VBA:

Sub k()

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

i = i + 1
Loop

End Sub

I’m using excel 2010 on windows 7.

Vega's user avatar

Vega

27.2k27 gold badges91 silver badges98 bronze badges

asked Jan 16, 2012 at 19:52

Diogo's user avatar

1

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

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


Update:

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

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

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

answered Jan 16, 2012 at 19:55

Devin Burke's user avatar

Devin BurkeDevin Burke

13.5k11 gold badges54 silver badges82 bronze badges

5

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

Thanks again!

Option Explicit

Sub k()

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

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

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

bpeterson76's user avatar

bpeterson76

12.9k4 gold badges48 silver badges82 bronze badges

answered Jan 17, 2012 at 16:50

Diogo's user avatar

DiogoDiogo

1511 gold badge1 silver badge5 bronze badges

1

Diogo

Justin has given you some very fine tips :)

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

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

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

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

Option Explicit

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

20        Application.ScreenUpdating = False

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

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

50        Set ws = Sheets(name)

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

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

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

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

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

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

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

answered Jan 16, 2012 at 23:15

Siddharth Rout's user avatar

Siddharth RoutSiddharth Rout

146k17 gold badges206 silver badges250 bronze badges

3

For future readers:

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

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

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

To solve it, I had to do this:

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

answered Jun 21, 2018 at 15:45

cssyphus's user avatar

cssyphuscssyphus

36.7k18 gold badges93 silver badges108 bronze badges

Sub HighlightSpecificValue()

'PURPOSE: Highlight all cells containing a specified values


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

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

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

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

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

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

  Else
    GoTo NothingFound
  End If

Set rng = FoundCell

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







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

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


  Loop

'Highlight Found cells yellow

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

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

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



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

  ElseIf FoundCell.Value("Nav") Then

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



    End If





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

Exit Sub

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

End Sub

Neil's user avatar

Neil

54k8 gold badges60 silver badges72 bronze badges

answered Oct 9, 2015 at 10:10

chetan dubey's user avatar

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

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

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

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

TylerH's user avatar

TylerH

20.5k62 gold badges75 silver badges97 bronze badges

answered Oct 11, 2013 at 19:14

Youbi's user avatar

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

enter image description here

answered Dec 13, 2016 at 21:12

gadolf's user avatar

gadolfgadolf

9879 silver badges19 bronze badges

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:

  1. Download Excel File Repair Tool rated Excellent by Softpedia, Softonic & CNET.
  2. Select the corrupt Excel file (XLS, XLSX) & click Repair to initiate the repair process.
  3. 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:

Excel Runtime Error 13 Type Mismatch

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”

Open-and-Repair

  • Lastly, click on the “Repair” button.

excel open and repair

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.

Reinstall The Microsoft Office Application

  • Here, you will get the list of installed programs on your PC.

ms office repair from control panel

  • Then from the list select Microsoft Work.
  • Click on uninstall to remove it from the PC.

Uninstall The Program

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.

enable excel macros 1

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

Copy Macros in the Personal Macro Workbook 3

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

Run The ‘Regedit’ Command In CMD

  • 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

Create New Disk Partition And Reinstall Windows 

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

Create New Disk Partition And Reinstall Windows  1

  • 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:

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 an entrepreneur & 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.

Working on MS Excel and suddenly an error notification stating, “Run-time error ‘13’: Type Mismatch” appears on your screen. It is a mismatch error that occurs at the time of the execution of code in MS Excel. This error may lead to the sudden termination of all activities going on in Excel.

Why does this Error happen?

There are many reasons why a user faces this error, let’s discuss a few of the most common reasons that lead to it:

  • If MS Excel conflicts with Operating System.
  • If any other program conflicts with MS Excel
  • If there is a virus attack
  • Mismatch of data type while trying to run a VBA file
  • Faulty or incorrectly configured MS Excel program
  • Corrupt or damaged Excel workbook.

How to Fix Runtime Error 13?

Just like any other problem, this error too has a solution to it, which we are going to discuss below. But it is always recommended to know the actual problem before moving to any solution. This will save you a lot of time. Let’s move towards the best possible solutions.

  • Run a Scan: Whenever there is an error or problem in your system, one of the main reasons behind is a virus attack. So, if you haven’t run an anti-virus scan yet, you need to do it now. Install reliable anti-virus software and run a scan on your system. This may solve your issue. If not, keep reading the blog.
  • Uninstall Recently Installed Applications: Sometimes, everything on the system keeps on working until some new applications or programs are installed. Sometimes a few of these programs start creating issues in the working of the system. So eventually, you need to uninstall any such program and see if it solves the problem for you.For this, first, you need to decide the programs you installed recently and might be creating this interruption. So, once you have figured it out, go to the Control Panel and search for Add or Remove program. This Add or Remove feature lets you manage all the programs and applications you are having in your system currently. Uninstall the program/application creating the problem and see if it solves the problem.
  • Try Open and Repair: Excel has an inbuilt repair utility of its own that can repair minor damages and corruption in the Excel workbook. To launch and run this utility, follow the below-mentioned steps:
    1. While still on Excel, click on the File option.
    2. Select Open from the category list.
    3. Click Browse to select the damaged or corrupt workbook.
    4. After selecting the file, check on the right corner, you will see a drop-down with Open option. Click on that drop-down and select Open and Repair from the options.Click on that drop-down and select Open and Repair from the options
    5. A Microsoft Excel dialogue box will appear asking for permission, select on the Repair button finally.

Try A Professional Approach

Excel Recovery is a reliable third-party utility that can fix Error 13 in Excel in a few easy steps. As we have discussed already, Error 13 is a runtime file error in MS Excel that occurs due to reasons like a damaged Excel file. This tool can successfully repair a damaged Excel file, along with all the items it contains. Let’ see a demo of the tool.

  1. To select an .XLS or .XLSX file, click on the Browse button.click on the Browse button
  2. Click on the Repair button to proceed.Click on the Repair button to proceed
  3. The tool will start scanning to repair the file. Wait for the process to get finished or click on the Stop button to discard the process.click on the Stop button to discard the process
  4. Once the scan and repair are done, you can have the preview of the Excel file.scan and repair
  5. To save the file, click on the Select Path button, provide a destination and click on the Save button.click on the Select Path button
  6. Once you click the save button, the tool will start saving the file to its fixed location. You can anytime click on the Stop button to discard the process.click on the Stop button
  7. Once the saving process is over, the tool will confirm its saving and provide you with a path where it is saved. Click on Back if changes are required.
    Click on Back

If you perform all of the above-mentioned steps carefully, you now will be able to use the Excel file without any interruption. This tool will surely fix the Error 13 you are facing in Excel.

Conclusion:

In this blog, we have discussed about Error 13 occurring in Excel, what it is, why you might be facing it, and how are you going to fix it. There are several ways to do it depending on the reason behind the error. We have discussed about four solutions, including an automated method, in which we have used Excel Repair to fix the damaged, corrupt Excel files or errors like Excel file is not in a recognizable format. This tool works like magic for XLS/XLSX files, recovering it with all its data including charts, tables, formulas, etc. Hope this blog helps you find the exact solution to your problem.

Download Now

Понравилась статья? Поделить с друзьями:
  • Ошибка runtime error 1004 vba
  • Ошибка runtime error 1004 excel
  • Ошибка runtime error 1004 application defined or object defined error
  • Ошибка run time error 9 subscript out of range
  • Ошибка rtx voice initialization failed