Excel VBA Run-time error '13' Type mismatch
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 ** **.
I’m using excel 2010 on windows 7.
![]()
7 Answers 7
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:
Note that your x value may not contain its expected value in the next iteration, however.
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.
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
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.
![]()
For future readers:
This function was abending in Run-time error ’13’: Type mismatch
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:
![]()
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.
Разбор ошибки 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.
- Запустите код, чтобы появилась ошибка.
- Нажмите Debug в диалоговом окне ошибки. Это выделит строку с ошибкой.
- Выберите View-> Watch из меню, если окно просмотра не видно.
- Выделите переменную слева от equals и перетащите ее в окно Watch.
- Выделите все справа от равных и перетащите его в окно Watch.
- Проверьте значения и типы каждого.
- Вы можете сузить ошибку, изучив отдельные части правой стороны.
Следующее видео показывает, как это сделать.
На скриншоте ниже вы можете увидеть типы в окне просмотра.

Используя окно просмотра, вы можете проверить различные части строки кода с ошибкой. Затем вы можете легко увидеть, что это за типы переменных.
В следующих разделах показаны различные способы возникновения 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. Есть очень тонкая разница.
- Worksheets — сборник рабочих листов в Workbook
- Sheets — сборник рабочих листов и диаграммных листов в Workbook
Лист диаграммы создается, когда вы перемещаете диаграмму на собственный лист, щелкая правой кнопкой мыши на диаграмме и выбирая «Переместить».
Если вы читаете коллекцию Sheets с помощью переменной Worksheet, она будет работать нормально, если у вас нет рабочей таблицы.
Если у вас есть лист диаграммы, вы получите
Type Mismatch Error VBA.
В следующем коде Type Mismatch Error появится в строке «Next sh», если рабочая книга содержит лист с диаграммой.
Массивы и диапазоны
Вы можете назначить диапазон массиву и наоборот. На самом деле это очень быстрый способ чтения данных.
Проблема возникает, если ваш диапазон имеет только одну ячейку. В этом случае VBA не преобразует arr в массив.
Если вы попытаетесь использовать его как массив, вы получите
Type Mismatch Error .
В этом сценарии вы можете использовать функцию IsArray, чтобы проверить, является ли arr массивом.
Заключение
На этом мы завершаем статью об Type Mismatch Error VBA. Если у вас есть ошибка несоответствия, которая не раскрыта, пожалуйста, дайте мне знать в комментариях.
Как исправить ошибку во время выполнения 13
«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, или к вирусам / вредоносному ПО.
VBA Type Mismatch Errors
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:

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.

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

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

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

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

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 5 th cell down has the text value and this has caused the code to fail

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
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
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:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

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
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.
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.
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:
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:
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
This code will return False because although the string begins with numeric characters, it also contains text so it fails the test.
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
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:

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:


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.