Microsoft visual basic runtime error 13 type mismatch

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

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

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

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

Excel VBA Run-time error ’13’ Type mismatch

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

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

VBA:

Sub k()

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

i = i + 1
Loop

End Sub

I’m using excel 2010 on windows 7.

Vega's user avatar

Vega

27.1k27 gold badges91 silver badges98 bronze badges

asked Jan 16, 2012 at 19:52

Diogo's user avatar

1

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

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


Update:

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

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

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

answered Jan 16, 2012 at 19:55

Devin Burke's user avatar

Devin BurkeDevin Burke

13.5k11 gold badges54 silver 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.

Содержание

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

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

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

Обзор «Type mismatch»

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Имя модуля

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

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

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

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

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

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

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

Коллекция Sheets

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

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

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

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

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

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

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

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

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

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

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

Заключение

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

Источник

Top 5 Techniques to Fix Microsoft Visual Basic Runtime Error 13 Type Mismatch in Excel

“Recently, I had created a macro for a file and at the first, it works fine. However, today when I opened and restarted the file, it throws an error message i.e., Microsoft Visual Basic Runtime Error 13 Type Mismatch in Excel. I did not change anything in the macro and I do not know why I am getting this error. Please, help!”

Are you acquiring the same error while running MS Excel and want to get rid of this? If yes, then, certainly you have landed on the right solution page. Here, we are going to discuss some simple and cost-efficient workarounds for the same. However, before going to the solution section, it is essential to know about the error message. So let us get started!

A Brief Introduction to MS Excel Runtime Error 13

The runtime error 13 is a mismatch error that normally occurs when one or more data files or the required processes to launch an application, which by default uses the Visual Basic (VB) environment. When the user tries to run a VBA code that comprises data types, which are not matched properly the ms excel vba runtime error 13 type mismatch appears. Apart from this, there are many reasons that may generate this Excel error. This error displays as “run-time error 13 – Type mismatch”.

  • Runtime Error 13 occurs due to conflicts between the program and operating system
  • When a macro is clicked on by the user or a missing menu function from the Excel file
  • Corrupted/ damaged registry or incomplete installation of Microsoft Excel software
  • Virus or malware attack that corrupts the Excel related or Windows system files
  • Conflicts with other applications while launching a VBA Excel file also causes the error

Techniques to Fix MS Excel runtime error 13 Type Mismatch

#Approach 1: Use Open and Repair Utility

To resolve the error code, users can utilize the Open and Repair tool to repair corrupted Excel file. It is an inbuilt utility to repair Excel files. Below are the guidelines for this:

  • Navigate to the File menu and click on Open
  • Now, choose the corrupt Excel file from the drop-down list of Open menu. Then, click on Open and Repair
  • Eventually, hit the Repair button

Note: The inbuilt repair utility cannot repair severely damaged Excel file. In such cases you can go for SysTools Excel Recovery Utility to resolve this issue.

#Approach 2: Uninstall the Application

If you found that some software causes the Microsoft Visual Basic Runtime Error 13 Type Mismatch in Excel then, you can simply uninstall the problematic program to get rid of the error.

  • For this, first, navigate to Task Manager and stop the running applications
  • Now, go to the Start menu and choose Control Panel
  • Here, select Programs >> Uninstall a program
  • Doing this will display a list of installed programs on your computer
  • Select Microsoft Work from the menu list and click on Uninstall to remove this application from PC

#Approach 3: Scan for Viruses or Malware

Virus and malware are one of the main cause to generate MS Excel Runtime Error 13 as they infect the user’s computer. If a malware or virus gets into the computer it not only replicates itself but, also corrupt the system files that may require to run certain applications of the computer. One can resolve the error via running a good antivirus program to detect the viruses and malware in PC.

#Approach 4: Repair Windows Registry

Corruption in Windows registry files also may cause of this error message. Thus, follow the below-guidelines to fix Windows registry:

  • In your PC, search for Windows Registry

  • In Windows registry editor open HKEY_LOCAL_MACHINE_Software
  • Click on Software and choose Microsoft >> Windows then, select Current version >> Run
  • Now, select the error file and Delete it
  • After this, reboot your system

#Approach 5: Recover Missing Macros

Missing macros may occur the MS Excel Runtime Error 13 so, one can try to recover the missing Macros via following steps:

  • Open a new Excel file and set calculation mode to Manual
  • Click on Tools >> Macro >> Security >> High option
  • If you are using Excel 2007 then, click on Office >> Excel Options >> Trust Center
  • Now, click on Trust Center Settings >> Macros Settings. Here, choose Disable All Macros without Notification in Macro Settings and click on OK >> OK

  • Open the corrupted workbook and if Excel opens it then, a message will appear that Macros are disabled
  • However, if Excel shut down then, this method is not working for you
  • Now, you have to press [Alt] + [F11] to open the Visual Basic Editor (VBE)
  • Use Project Explorer (press Ctrl+R keys) and hit a right-click on a module and Export File
  • Type a name and folder for a module and repeat this step as many times as you need to export the entire modules
  • Eventually, close the VBE and Exit

After this, open a new blank workbook or the recently created workbook, which contains recovered data from the corrupted workbook. Then, import the modules. This will resolve runtime error 13.

Concluding Lines

Microsoft Visual Basic Runtime Error 13 Type Mismatch in Excel is a commonly found Excel file error. In order to resolve this error, we have come up with this technical paper. Here, we have disclosed simple techniques to fix it. Now, it is all up to users that which solution they want to opt.

Facing error with Excel application that you use in your day to day routine, whether regularly or seldom; at home or in the workplace, is unquestionably an undesired circumstance. The problem increases when the error that you have found, is remote or for the first time. Both MS Excel XLS and XLSX files become unreliable or corrupt at times and may return different errors including Microsoft visual basic runtime error 13 type mismatch in excel.

win download

Other
than Excel runtime 1004, 32809, 57121 error; Excel Runtime Error 13 also
affects MS Excel or its XLS/XLSX files. If you have no idea to resolve the
error as fast as possible, it is obvious you to get baffled. This technical
post is a purpose to assist you to resolve the runtime error 13. So know the
error: its causes and fixes here.

Introduction to MS Excel Runtime Error 13

The
Excel runtime file error 13 is a type of mismatch error in MS Excel. Normally,
it arises when one or more files or methods are needed to begin a program that
operates the Visual Basic (VB) environment by default. This means the error
occurs when Excel users try to run VBA code including data types that are not
met in the correct manner. Consequently, ‘runtime error 13: type mismatch
Excel’ appears in Microsoft Excel.

What causes runtime error 13 type mismatch in excel?

Following
are the reason for runtime error 13 in excel:

  • Flawed or unfinished installation of
    MS Excel application in the system.
  • The clash between the Excel
    application program and Win operating system.
  • When the user clicks a missing menu
    function or a macro from an Excel file.
  • A faulty code infection or
    virus/malware attack makes excel files prone to corruption.
  • Collide with other programs while
    launching a VBA Excel file.

Techniques to Resolve MS Excel runtime error 13 Type Mismatch Excel

#Technique 1: Using Open and
Repair Utility

The
MS Excel automatically provides ‘File Recovery’ mode when it detects a
corrupted workbook or worksheet. It does this to fix the damaged Excel files.
But sometimes  Excel does not give the
‘File Recovery’ mode automatically. This is the time when you can use ‘Open and
Repair’, an inbuilt utility in Excel to restore damaged Excel files. Use this
technique to fix Microsoft visual basic runtime error 13 type mismatch in Excel:

  • Open Excel application.
  • Navigate to the File menu and click
    on the Open button.
  • Choose the ‘Excel’ file.
  • Click the ‘Open’ dropdown list.
  • ­Click the ‘Open and Repair’ button.
  • Click the ‘Repair’ button to recover
    maximum possible data Or Click the ‘Extract Data’ tab to secure values and
    formulae.

#Technique 2:  Uninstall the ‘error causing excel’

It is observed that unusual applications programs and software
cause runtime error. Uninstall those applications or software to fix the Excel
file runtime error. To do so, the actions are:

  • Go to ‘Task Manager’ and stop the error
    causing programs one by one.
  • Click the ‘Start’ menu.
  • Click ‘Control Panel’ button.
  • Select ‘Add or Remove Program’ in Control
    Panel.
  • All the installed programs on the PC are
    enlisted.
  • Select MS Excel and click ‘Uninstall’ to
    remove it from the PC.

#Technique 3: Repair Windows Registry

  • Navigate to Windows Registry on your
    PC.
  • In Windows registry editor open
    HKEY_LOCAL_MACHINE_Software.
  • Click on Software and select
    Microsoft >> Windows then, select Current version >> Run.
  • Now, choose the error file and
    Delete it.
  • After here, reboot your system.

#Technique 4: Use SysInfoTools Excel Repair
Software

An expert Excel file repair software by SysInfoTools that strongly repairs infected Excel XLS and XLSX files without any trouble. Recover all-important Excel file components: table, chart, chart sheet, formula, cell comment, image, sort, filter, etc. without data loss or change in the structure or data alteration of the files. With a user-friendly and habitual interface having quickly accessible tabs, buttons, and menus, the Excel file repair process is easy and saves time.

Final Verdict

This blog explains Microsoft visual basic runtime error 13 type mismatch in Excel in detail. Now you can fix Excel runtime error by using any of the above-discussed techniques. If you want to learn How to Recover Unsaved Excel File Windows then read here. I hope you like the post. Thanks

Summary:
The Excel runtime error 13 can occur while running Excel VBA projects. The Excel users triggers this error if there is a mismatch in datatype in the VBA code. Additionally, there can be other causes. This blog will discuss the possible causes of the error and their solutions. It also mentions Stellar Repair for Excel if the runtime error 13 occurs due to corruption in the Excel file.

Free Download for Windows

Contents

  • Excel Runtime Error 13
  • Causes for Excel Runtime Error 13
  • Fixes
  • Limitations
  • Conclusion

Encountering error with Excel application that you use every day, whether frequently or sometimes; at home or in office, is undoubtedly an unwanted situation. The trouble doubles when the error that you have encountered, is unknown or for the first time. Both Excel XLS and XLSX files become corrupt or damaged at times and may return different errors including runtime errors.

A runtime error that commonly affects MS Excel or its XLS/XLSX files other than Excel runtime 1004, 32809, 57121 error, etc. is Excel Runtime Error 13. Not knowing what to do when there is a time constraint to resolve the error, it is evident for you to get perplexed. This blog is an intent to help you resolve the terrible situation you are experiencing due to runtime error 13. Know all about the error: what is it, its causes and the fixes.

Excel Runtime Error 13

The VBA runtime file error 13 is a type of mismatch error in Excel. Usually, it arises when one or more files or processes are required to launch a program that employs the Visual Basic (VB) environment by default. This means the error occurs when Excel users try to run VBA code containing data types that are not matched in the correct manner. Consequently, ‘runtime error 13: type mismatch Excel’ appears in Excel.

Causes for Excel Runtime Error 13

The Excel runtime error 13 causes are as follows:

  1. Damaged or incomplete installation of MS Excel application
  2. The conflict between the Excel application and Operating System
  3. When a missing menu function or a macro is clicked on by the user from Excel file
  4. Virus/malware attack or malicious code infection damaging Excel files
  5. Conflict with other programs while VBA Excel file is open

Fixes

The methods to fix Excel runtime error 13 are as follows:

Fix 1: Make use of the ‘Open and Repair’ utility

MS Excel automatically provides ‘File Recovery’ mode when it discovers a damaged workbook or worksheet. It does this to repair the damaged Excel files. But there are times when Excel does not provide the ‘File Recovery’ mode automatically. This is the time when you can employ ‘Open and Repair’, an inbuilt utility to repair Excel files. The steps to use this utility are:

  1. Open Excel application
  2. Go to File->Open
  3. Select the ‘Excel’ file
  4. Click the ‘Open’ dropdown
  5. ­Click ‘Open and Repair..’ button

Stellar

  1. Click ‘Repair’ button to recover as much work as possible Or Click ‘Extract Data’ tab to extract values and formulae

Note: If Open and Repair process is not successful using ‘Repair’ option, use ‘Extract Data’

Fix 2: Uninstall the ‘error causing program’

It is found that some application and software cause the runtime error. Uninstall those application or software to fix the Excel file runtime error. To do so, the steps are:

  1. Go to ‘Task Manager’ and stop the error causing programs one by one
  2. Click ‘Start’ menu
  3. Click ‘Control Panel’ button
  4. Select ‘Add or Remove Program’ or “uninstall a program” option in Control Panel

Image of Control Panel > Programs

  1. All the installed programs on the PC is enlisted
  2. Select MS Office and click ‘Uninstall’ to remove it from the PC

Image of Microsoft Office being uninstalled from Control Panel

Limitations

Using Microsoft’s Open & Repair Utility and uninstalling error causing software-programs may or may not resolve Excel Runtime Error 13. In that case a sure-shot and reliable software helps in resolving the error.

Fix 3: Use Stellar Repair for Excel

A professional Excel file repair software that successfully repairs damaged Excel .XLS and .XLSX files without hassle. Recovers all important Excel file components: table, chart, chart sheet, formula, cell comment, image, sort, filter, etc. without data loss or change in the structure or formatting of the files. With a user-friendly and intuitive interface having easily accessible tabs, buttons, and menus, the Excel repair process is easy and saves time.

Free download

Conclusion

You are now aware of the Excel runtime error 13, its causes and steps to resolve it, if the same occurs in Excel XLS/XLSX file. All the three fixes that the blog suggests, are effective in addressing the error. However, Stellar Repair for Excel makes your task of removing Excel runtime errors easy while offering multiple advantages. The software shows a preview of the repaired Excel file data before saving it. Along with resolving Excel Runtime Error 13, the software also resolves other errors associated with MS Excel. Further, it maintains workbook properties, cell formatting and overall structure to provide the real-time recovery of Excel file.

About The Author

Priyanka

Priyanka is a technology expert working for key technology domains that revolve around Data Recovery and related software’s. She got expertise on related subjects like SQL Database, Access Database, QuickBooks, and Microsoft Excel. Loves to write on different technology and data recovery subjects on regular basis. Technology freak who always found exploring neo-tech subjects, when not writing, research is something that keeps her going in life.

Best Selling Products


Stellar Repair for Excel

Stellar Repair for Excel

Stellar Repair for Excel software provid

Read More


Stellar Toolkit for File Repair

Stellar Toolkit for File Repair

Microsoft office file repair toolkit to

Read More


Stellar Repair for QuickBooks ® Software

Stellar Repair for QuickBooks ® Software

The most advanced tool to repair severel

Read More


Stellar Repair for Access

Stellar Repair for Access

Powerful tool, widely trusted by users &

Read More

VBA Type Mismatch

Excel VBA Type Mismatch

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

How to Fix Type Mismatch Error in VBA?

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

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

Example #1 – VBA Type Mismatch

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

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

Insert Module

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

Code:

Sub VBA_TypeMismatch()

End Sub

VBA Type Mismatch Example 1-1

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

Code:

Sub VBA_TypeMismatch()

Dim A As Integer

End Sub

VBA Type Mismatch Example 1-2

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

Code:

Sub VBA_TypeMismatch()

Dim A As Integer
A = "Ten"

End Sub

Integer Data Type Example 1-3

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

Code:

Sub VBA_TypeMismatch()

Dim A As Integer
A = "Ten"
MsgBox A

End Sub

VBA Type Mismatch Example 1-4

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

VBA Type Mismatch Example 1-5

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

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

Code:

Sub VBA_TypeMismatch()

Dim A As Integer
A = 10
MsgBox A

End Sub

VBA Type Mismatch Example 1-6

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

VBA Type Mismatch Example 1-7

Example #2 – VBA Type Mismatch

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

Step 1: Write the subprocedure for VBA Type Mismatch.

Code:

Sub VBA_TypeMismatch2()

End Sub

VBA Type Mismatch Example 2-1

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

Code:

Sub VBA_TypeMismatch2()

Dim A As Byte

End Sub

VBA Type Mismatch Example 2-2

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

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

Code:

Sub VBA_TypeMismatch2()

Dim A As Byte
A = "Ten"

End Sub

VBA Type Mismatch Example 2-3

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

Code:

Sub VBA_TypeMismatch2()

Dim A As Byte
A = "Ten"
MsgBox A

End Sub

VBA Type Mismatch Example 2-4

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

VBA Type Mismatch Example 2-5

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

Code:

Sub VBA_TypeMismatch2()

Dim A As Byte
A = 1000
MsgBox A

End Sub

VBA Type Mismatch Example 2-6

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

Run-Time Error ‘6 Example 2-7

Example #3 – VBA Type Mismatch

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

Step 1: Write the subprocedure for VBA Type Mismatch.

Code:

Sub VBA_TypeMismatch3()

End Sub

Excel VBA Type Mismatch Example 3-1

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

Code:

Sub VBA_TypeMismatch3()

Dim A As Integer
Dim B As Integer

End Sub

VBA Type Mismatch Example 3-2

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

Code:

Sub VBA_TypeMismatch3()

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

End Sub

VBA Type Mismatch Example 3-3

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

Code:

Sub VBA_TypeMismatch3()

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

End Sub

Message Box Example 3-4

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

Run-time error ’13 Example 3-5

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

Code:

Sub VBA_TypeMismatch4()

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

End Sub

Integer to Long Example 3-6

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

VBA Type Mismatch Example 3-8

Pros of VBA Type Mismatch:

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

Things to Remember

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

Recommended Articles

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

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

Понравилась статья? Поделить с друзьями:
  • Microsoft visual foxpro error 1429
  • Microsoft visual basic runtime error 1004 как исправить
  • Microsoft visual c выдает ошибку runtime error
  • Microsoft visual basic run time error 438
  • Microsoft visual c runtime stray ошибка