Плавающая ошибка — runtime error 13 — type mismatch
Ошибка runtime error 13 — type mismatch
Здравствуйте Есть программа, которая переводит числа из двоичной сс в десятичную сс, она работает.
OpenRecordset и ошибка — несоответствие типа. runtime error(13) Type mismatch
У меня возникла следующая проблема: После того как на компьютере вместо Office 97 установили .
Ошибка runtime error 13 — type mismatch при выполнении простого макроса
Здравствуйте! Была поставлена задача сделать таблицу с кнопками-макросами, чтобы при нажатии на.
Runtime error 13 — type mismatch — VBA
Привет всем ! У меня тут не сходится, взгляните, если не сложно. Private Sub.
Это не "баг". Это "отсутствие проверки входных данных".
При калькуляции возникает ситуация, когда код пытается сконвертировать текстовое значение "-" в число.
Ессессно, у VB это не выходит.
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.
Runtime Error 13: Type Mismatch [Fix]
Reinstall the problematic program incase of installation errors
- Run-time errors usually occur when a program tries to execute a process that is impossible or when there is an error in the data it is trying to interpret.
- Always ensure your software is up-to-date to rule out compatibility issues, as this is the most common cause behind the run time error.

Runtime error 13 is a common error when you try to run an application on a computer that does not have the correct version of the runtime libraries installed. Most users say they encounter this error when opening a Microsoft Excel file.
The most common reason this error occurs is that the program was written for one version of an operating system and is being run on another. For example, if you try to run Windows 11 software on Windows 8, you may get such an error.
What is error 13 at run time mismatch?
Error 13 is a run-time error that occurs when Microsoft Excel cannot find the correct function or macro to do the task you are trying to perform.
This mainly occurs when an application fails to initialize its resources because of an incompatibility between the application and the operating system.
It’s likely to happen if the application was developed for an older version of Windows or if it’s incompatible with the version you’re running.
Other reasons include:
- Missing files – If there are missing files in your system, then it will cause this error. Some third-party applications may delete some files from your system that Windows requires to run properly.
- Corrupted DLLs and EXE files – Corrupted DLLs and EXE files can also cause the error 13 at runtime mismatch because Windows requires these files to execute different programs.
- Virus infection – If a virus finds its way to your system, it can infect system-related files, including Excel files, and cause this error.
- Incorrect installation/uninstallation – Improperly uninstalling a previous version of an application and then installing it again without uninstalling it completely can also cause this runtime error.
How do I fix Runtime Error 13?
A few workarounds that could resolve this issue include:
-
and install them if available.
- Ensure you’re running the latest version of Excel. .
1. Use the Program Compatibility Checker
- Hit the Windows key, type Program Compatibility Checker, and click on Open under Run programs for previous versions of Windows.

- On the Program Compatibility Checker window, click Next.

- From the next window, scroll and select the program; in this case it is Excel. Click Next.

- Click on Troubleshoot program.

- Now select the most suitable option presented under What problems do you notice?
- Click Next.

- You might have to repeat the process with different options to see what resolves the error.
2. Repair Excel
- Launch MS Excel and open a blank workbook.
- Click on File.

- Select Open and click on Browse.

- Locate the problematic file, select it, and click on the drop-down icon next to Open.

- Select Open and Repair.

If this fixes the issue, good, but if it doesn’t, you can try out the automatic Excel repair tools, which are more thorough.
3. Run the Program Install and Uninstall troubleshooter
-
and install it.
- Launch it and click on Next.

- You’ll be asked whether you have a problem installing or uninstalling a program. Select one option.

- Next, you’ll be asked to select the program that is not installing. Pick the problematic program from the list.

- The troubleshooter will start scanning for problems.

- Once it completes, you’ll be presented with two options. Pick either and wait for the troubleshooter to recommend fixes.

4. Scan for viruses
- Click on the Start Menu icon, search Windows Security, and click Open.

- Select Virus & threat protection.

- Next, press Quick scan under Current threats.

- If you don’t find any threats, proceed to perform a full scan by clicking on Scan options just below Quick scan.

- Click on Full scan, then Scan now to perform a deep scan of your PC.

- Wait for the process to finish and restart your system.
5. Run Excel in compatibility mode

- Locate the .exe file of the problematic problem usually in one of the following paths depending on your version of Windows: C:\Program Files (x86) or C:\Program Files
- Scroll down until you find the program you’re looking for.
- Right-click on the .exe file of the program and select Properties.
- Navigate to the Compatibility tab, check the Run this program in Compatibility mode option, and select Windows 8 from the drop-down menu.
- Allow the program to finish installing, then check whether the error persists.
6. Reinstall Excel
- Click the Start button and select Settings.

- Choose Apps from the left pane and click on Installed apps from the right.

- Look for the Office suite in the list of apps, click the three dots icon from its right, and select Uninstall.
- Go to the official Office 365 website and sign into your account.

- Now, from the main Microsoft 365 account, click on Install Office.

You may also come across runtime error 217 but worry not, as we have also laid down an easy fix guide to help you resolve the issue.
Speaking of runtime errors, we’d also like to recommend installing runtime repair tools to help you easily navigate such issues.
That’s it for this article, but let us know which solution fixed this error for you in the comment section below.
Разбор ошибки 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. Если у вас есть ошибка несоответствия, которая не раскрыта, пожалуйста, дайте мне знать в комментариях.