VBA – Type Mismatch (Run-time Error 13)

Written by

Editorial Team

Reviewed by

Steve Rynearson

Last updated on July 19, 2021

VBA Type Mismatch Errors

What is a Type Mismatch Error?

A mismatch error can often occur when you run your VBA code.  The error will stop your code from running completely and flag up by means of a message box that this error needs sorting out

Note that if you have not fully tested your code before distribution to users, this error message will be visible to users, and will cause a big loss of confidence in your Excel application.  Unfortunately, users often do very peculiar things to an application and are often things that you as the developer never considered.

A type mismatch error occurs because you have defined a variable using the Dim statement as a certain type e.g. integer, date, and your code is trying to assign a value to the variable which is not acceptable e.g. text string assigned to an integer variable as in this example:

Here is an example:

PIC 01

Click on Debug and the offending line of code will be highlighted in yellow.  There is no option on the error pop-up to continue, since this is a major error and there is no way the code can run any further.

In this particular case, the solution is to change the Dim statement to a variable type that works with the value that you are assigning to the variable. The code will work if you change the variable type to ‘String’, and you would probably want to change the variable name as well.

PIC 02

However, changing the variable type will need your project resetting, and you will have to run your code again right from the beginning again, which can be very annoying if a long procedure is involved

PIC 03

Mismatch Error Caused by Worksheet Calculation

The example above is a very simple one of how a mismatch error can be produced and, in this case, it is easily remedied

However, the cause of mismatch errors is usually far deeper than this, and is not so obvious when you are trying to debug your code.

As an example, suppose that you have written code to pick up a value in a certain position on a worksheet and it contains a calculation dependent other cells within the workbook (B1 in this example)

The worksheet looks like this example, with a formula to find a particular character within a string of text

PIC 04

From the user’s point of view, cell A1 is free format and they can enter any value that they want to.  However, the formula is looking for an occurrence of the character ‘B’, and in this case it is not found so cell B1 has an error value.

The test code below will produce a mismatch error because a wrong value has been entered into cell A1

Sub TestMismatch()
Dim MyNumber As Integer
MyNumber = Sheets("Sheet1").Range("B1").Value
End Sub

The value in cell B1 has produced an error because the user has entered text into cell A1 which does not conform to what was expected and it does not contain the character ‘B’

The code tries to assign the value to the variable ‘MyNumber’ which has been defined to expect an integer, and so you get a mismatch error.

This is one of these examples where meticulously checking your code will not provide the answer. You also need to look on the worksheet where the value is coming from in order to find out why this is happening.

The problem is actually on the worksheet, and the formula in B1 needs changing so that error values are dealt with. You can do this by using the ‘IFERROR’ formula to provide a default value of 0 if the search character is not found

PIC 05

You can then incorporate code to check for a zero value, and to display a warning message to the user that the value in cell A1 is invalid

Sub TestMismatch()
Dim MyNumber As Integer
MyNumber = Sheets("Sheet1").Range("B1").Text
If MyNumber = 0 Then
    MsgBox "Value at cell A1 is invalid", vbCritical
    Exit Sub
End If
End Sub

You could also use data validation (Data Tools group on the Data tab of the ribbon) on the spreadsheet to stop the user doing whatever they liked and causing worksheet errors in the first place. Only allow them to enter values that will not cause worksheet errors.

You could write VBA code based on the Change event in the worksheet to check what has been entered.

Also lock and password protect the worksheet, so that the invalid data cannot be entered

 

Mismatch Error Caused by Entered Cell Values

Mismatch errors can be caused in your code by bringing in normal values from a worksheet (non-error), but where the user has entered an unexpected value e.g. a text value when you were expecting a number.  They may have decided to insert a row within a range of numbers so that they can put a note into a cell explaining something about the number. After all, the user has no idea how your code works and that they have just thrown the whole thing out of kilter by entering their note.

PIC 06

The example code below creates a simple array called ‘MyNumber’ defined with integer values

The code then iterates through a range of the cells from A1 to A7, assigning the cell values into the array, using a variable ‘Coun’ to index each value

When the code reaches the text value, a mismatch error is caused by this and everything grinds to a halt

By clicking on ‘Debug’ in the error pop-up, you will see the line of code which has the problem highlighted in yellow. By hovering your cursor over any instance of the variable ‘Coun’ within the code, you will be able to see the value of ‘Coun’ where the code has failed, which in this case is 5

Looking on the worksheet, you will see that the 5th cell down has the text value and this has caused the code to fail

PIC 07

You could change your code by putting in a condition that checks for a numeric value first before adding the cell value into the array

Sub TestMismatch()
Dim MyNumber(10) As Integer, Coun As Integer
Coun = 1
Do
    If Coun = 11 Then Exit Do
    If IsNumeric(Sheets("sheet1").Cells(Coun, 1).Value) Then
            MyNumber(Coun) = Sheets("sheet1").Cells(Coun, 1).Value
    Else
            MyNumber(Coun) = 0
    End If
    Coun = Coun + 1
Loop
End Sub

The code uses the ‘IsNumeric’ function to test if the value is actually a number, and if it is then it enters it into the array. If it is not number then it enters the value of zero.

This ensures that the array index is kept in line with the cell row numbers in the spreadsheet.

You could also add code that copies the original error value and location details to an ‘Errors’ worksheet so that the user can see what they have done wrong when your code is run.

The numeric test uses the full code for the cell as well as the code to assign the value into the array.  You could argue that this should be assigned to a variable so as not to keep repeating the same code, but the problem is that you would need to define the variable as a ‘Variant’ which is not the best thing to do.

You also need data validation on the worksheet and to password protect the worksheet.  This will prevent the user inserting rows, and entering unexpected data.

Mismatch Error Caused by Calling a Function or Sub Routine Using Parameters

When a function is called, you usually pass parameters to the function using data types already defined by the function. The function may be one already defined in VBA, or it may be a User Defined function that you have built yourself. A sub routine can also sometimes require parameters

If you do not stick to the conventions of how the parameters are passed to the function, you will get a mismatch error

Sub CallFunction()
Dim Ret As Integer
Ret = MyFunction(3, "test")
End Sub

Function MyFunction(N As Integer, T As String) As String
MyFunction = T
End Function

There are several possibilities here to get a mismatch error

The return variable (Ret) is defined as an integer, but the function returns a string. As soon as you run the code, it will fail because the function returns a string, and this cannot go into an integer variable.  Interestingly, running Debug on this code does not pick up this error.

If you put quote marks around the first parameter being passed (3), it is interpreted as a string, which does not match the definition of the first parameter in the function (integer)

If you make the second parameter in the function call into a numeric value, it will fail with a mismatch because the second parameter in the string is defined as a string (text)

 

Mismatch Error Caused by using Conversion Functions in VBA Incorrectly

There are a number of conversion functions that your can make use of in VBA to convert values to various data types. An example is ‘CInt’ which converts a string containing a number into an integer value.

If the string to be converted contains any alpha characters then you will get a mismatch error, even if the first part of the string contains numeric characters and the rest is alpha characters e.g. ‘123abc’

 

General Prevention of Mismatch Errors

We have seen in the examples above several ways of dealing with potential mismatch errors within your code, but there are a number of other ways, although they may not be the best options:

Define your variables as Variant Type

A variant type is the default variable type in VBA. If you do not use a Dim statement for a variable and simply start using it in your code, then it is automatically given the type of Variant.

A Variant variable will accept any type of data, whether it is an integer, long integer, double precision number, boolean, or text value. This sounds like a wonderful idea, and you wonder why everyone does not just set all their variables to variant.

However, the variant data type has several downsides. Firstly, it takes up far more memory than other data types.  If you define a very large array as variant, it will swallow up a huge amount of memory when the VBA code is running, and could easily cause performance issues

Secondly, it is slower in performance generally, than if you are using specific data types.  For example, if you are making complex calculations using floating decimal point numbers, the calculations will be considerably slower if you store the numbers as variants, rather than double precision numbers

Using the variant type is considered sloppy programming, unless there is an absolute necessity for it.

 

 

Use the OnError Command to Handle Errors

The OnError command can be included in your code to deal with error trapping, so that if an error does ever occur the user sees a meaningful message instead of the standard VBA error pop-up

Sub ErrorTrap()
Dim MyNumber As Integer
On Error GoTo Err_Handler
MyNumber = "test"
Err_Handler:
MsgBox "The error " & Err.Description & " has occurred"
End Sub

This effectively prevents the error from stopping the smooth running of your code and allows the user to recover cleanly from the error situation.

The Err_Handler routine could show further information about the error and who to contact about it.

From a programming point of view, when you are using an error handling routine, it is quite difficult to locate the line of code the error is on. If you are stepping through the code using F8, as soon as the offending line of code is run, it jumps to the error handling routine, and you cannot check where it is going wrong.

A way around this is to set up a global constant that is True or False (Boolean) and use this to turn the error handling routine on or off using an ‘If’ statement.  When you want to test the error all you have to do is set the global constant to False and the error handler will no longer operate.

Global Const ErrHandling = False
Sub ErrorTrap()
Dim MyNumber As Integer
If ErrHandling = True Then On Error GoTo Err_Handler
MyNumber = "test"
Err_Handler:
MsgBox "The error " & Err.Description & " has occurred"
End Sub

The one problem with this is that it allows the user to recover from the error, but the rest of the code within the sub routine does not get run, which may have enormous repercussions later on in the application

Using the earlier example of looping through a range of cells, the code would get to cell A5 and hit the mismatched error.  The user would see a message box giving information on the error, but nothing from that cell onwards in the range would be processed.

 

VBA Programming | Code Generator does work for you!

Use the OnError Command to Supress Errors

This uses the ‘On Error Resume Next’ command. This is very dangerous to include in your code as it prevents any subsequent errors being shown.  This basically means that as your code is executing, if an error occurs in a line of code, execution will just move to the next available line without executing the error line, and carry on as normal.

This may sort out a potential error situation, but it will still affect every future error in the code. You may then think that your code is bug free, but in fact it is not and parts of your code are not doing what you think it ought to be doing.

There are situations where it is necessary to use this command, such as if you are deleting a file using the ‘Kill’ command (if the file is not present, there will be an error), but the error trapping should always be switched back on immediately after where the potential error could occur using:

On Error Goto 0

In the earlier example of looping through a range of cells, using ‘On Error Resume Next’, this would enable the loop to continue, but the cell causing the error would not be transferred into the array, and the array element for that particular index would hold a null value.

 

Converting the Data to a Data Type to Match the Declaration

You can use VBA functions to alter the data type of incoming data so that it matches the data type of the receiving variable.

You can do this when passing parameters to functions.  For example, if you have a number that is held in a string variable and you want to pass it as a number to a function, you can use CInt

There are a number of these conversion functions that can be used, but here are the main ones:

CInt – converts a string that has a numeric value (below + or – 32,768) into an integer value. Be aware that this truncates any decimal points off

CLng – Converts a string that has a large numeric value into a long integer.  Decimal points are truncated off.

CDbl – Converts a string holding a floating decimal point number into a double precision number.  Includes decimal points

CDate – Converts a string that holds a date into a date variable. Partially depends on settings in the Windows Control Panel and your locale on how the date is interpreted

CStr – Converts a numeric or date value into a string

When converting from a string to a number or a date, the string must not contain anything other that numbers or a date.  If alpha characters are present this will produce a mismatch error. Here is an example that will produce a mismatch error:

Sub Test()
MsgBox CInt("123abc")
End Sub

Testing Variables Within Your Code

You can test a variable to find out what data type it is before you assign it to a variable of a particular type.

For example, you could check a string to see if it is numeric by using the ‘IsNumeric’ function in VBA

MsgBox IsNumeric("123test")

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

MsgBox IsNumeric("123")

This code will return True because it is all numeric characters

There are a number of functions in VBA to test for various data types, but these are the main ones:

IsNumeric – tests whether an expression is a number or not

IsDate – tests whether an expression is a date or not

IsNull – tests whether an expression is null or not. A null value can only be put into a variant object otherwise you will get an error ‘Invalid Use of Null’. A message box returns a null value if you are using it to ask a question, so the return variable has to be a variant. Bear in mind that any calculation using a null value will always return the result of null.

IsArray – tests whether the expression represents an array or not

IsEmpty – tests whether the expression is empty or not.  Note that empty is not the same as null. A variable is empty when it is first defined but it is not a null value

 

Surprisingly enough, there is no function for IsText or IsString, which would be really useful

 

Objects and Mismatch Errors

If you are using objects such as a range or a sheet, you will get a mismatch error at compile time, not at run time, which gives you due warning that your code is not going to work

Sub TestRange()
Dim MyRange As Range, I As Long
Set MyRange = Range("A1:A2")
I = 10
x = UseMyRange(I)
End Sub
Function UseMyRange(R As Range)
End Function

This code has a function called ‘UseMyRange’ and a parameter passed across as a range object. However, the parameter being passed across is a Long Integer which does not match the data type.

When you run VBA code, it is immediately compiled, and you will see this error message:

PIC 08

The offending parameter will be highlighted with a blue background

Generally, if you make mistakes in VBA code using objects you will see this error message, rather than a type mismatch message:

PIC 09

vba-free-addin

VBA Code Examples Add-in

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

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

(No installation required!)

Free Download

Return to VBA Code Examples