I have the following code as part of my sub trying to assign a range:
'Set xlApp = CreateObject("Excel.Application")
Dim xlApp As Object
Set xlApp = GetObject(, "Excel.Application")
xlApp.Visible = False
xlApp.ScreenUpdating = False
Dim CRsFile As String
Dim CRsMaxRow As Integer
' get the CR list
CRsFile = "CRs.xls"
Set CRsWB = xlApp.Workbooks.Open("C:Docs" + CRsFile)
With CRsWB.Worksheets("Sheet1")
.Activate
CRsMaxRow = .Range("A1").CurrentRegion.Rows.Count
Set CRs = .Range("A2:M" & CRsMaxRow)
End With
Dim interestingFiles As Range
' get the files names that we consider interesting to track
Set FilesWB = xlApp.Workbooks.Open("files.xlsx")
With FilesWB.Worksheets("files")
.Activate
Set interestingFiles = .Range("A2:E5")
End With
Do you have any idea why am I getting a run time type mismatch error?
asked May 5, 2013 at 12:51
If you run the code from Word then the problem is in the declaration of ‘interestingFiles’ variable. Range exist in Word as well so use either Variant or add reference to Excel and then use Excel.Range.
Without Excel reference:
Dim interestingFiles As Variant
And with Excel reference:
Dim interestingFiles As Excel.Range
answered May 5, 2013 at 16:04
Daniel DušekDaniel Dušek
13.6k5 gold badges35 silver badges51 bronze badges
2
Kindly set xlApp object as in below code.
Also you provide complete path for your workbook when opening it.
Sub test()
Dim interestingFiles As Range
Dim xlApp As Object
Set xlApp = GetObject(, "Excel.Application")
' get the files names
Dim path As String
path = "C:UsersSantoshDesktopfile1.xlsx"
Set FilesWB = xlApp.Workbooks.Open(path)
With FilesWB.Worksheets(1)
.Activate
Set interestingFiles = .Range("A2:E5")
End With
End Sub
answered May 5, 2013 at 13:00
SantoshSantosh
12.1k4 gold badges41 silver badges72 bronze badges
10
maksdemon 0 / 0 / 0 Регистрация: 13.07.2014 Сообщений: 16 |
||||
1 |
||||
13.07.2014, 14:07. Показов 20824. Ответов 29 Метки нет (Все метки)
Доброе время суток.. При наладку 1с предприятия столкнулся с макросом который выводит бак код на весы.. В нем следуящая ошибка
Сам я в макросах не очень.. Подскажите в чем тут проблема
0 |
6878 / 2810 / 534 Регистрация: 19.10.2012 Сообщений: 8,573 |
|
13.07.2014, 14:39 |
2 |
На какой строке ошибка?
0 |
0 / 0 / 0 Регистрация: 13.07.2014 Сообщений: 16 |
|
13.07.2014, 14:54 [ТС] |
3 |
строка 38
0 |
призрак 3261 / 889 / 119 Регистрация: 11.05.2012 Сообщений: 1,702 Записей в блоге: 2 |
|
13.07.2014, 15:19 |
4 |
StrNew не число.
0 |
0 / 0 / 0 Регистрация: 13.07.2014 Сообщений: 16 |
|
13.07.2014, 15:24 [ТС] |
5 |
Если меняю значение на Val выдается ашибка Argument not optional. Усли на CLng то ошибка в синкасизе
0 |
призрак 3261 / 889 / 119 Регистрация: 11.05.2012 Сообщений: 1,702 Записей в блоге: 2 |
|
13.07.2014, 16:19 |
6 |
у val всего один аргумент в принципе — в зависимости от ваших данных, StrNew может вообще остаться неинициализированной (пустой)
ашибка
Усли
синкасизе
следуящая завязывайте вы с этим, а?
0 |
0 / 0 / 0 Регистрация: 13.07.2014 Сообщений: 16 |
|
13.07.2014, 16:32 [ТС] |
7 |
Я дико извиняюсь. Пишу в торопях. И все же какой выход в этой ситуации? 1с с этого макроса не запускается. Причины по которым произошел сбой мне неизвестны.
0 |
Заблокирован |
|
13.07.2014, 17:34 |
8 |
Val(StrNew) или CLng(StrNew) Val может вернуть число, но сделать может так… я пишу Debug.Print Val(«9,1»)
0 |
0 / 0 / 0 Регистрация: 13.07.2014 Сообщений: 16 |
|
13.07.2014, 17:38 [ТС] |
9 |
Val может вернуть число, но сделать может так… я пишу Debug.Print Val(«9,1») Т.е что в данном конкретном случае можете порекомендовать Вы?
0 |
Заблокирован |
||||
13.07.2014, 17:48 |
10 |
|||
ашибка Argument not optional … Добавлено через 8 минут
0 |
0 / 0 / 0 Регистрация: 13.07.2014 Сообщений: 16 |
|
13.07.2014, 17:53 [ТС] |
11 |
Скорее всего StrNew пустой, я код не запускал, так догадался, Прошу прощения.. Я в VBA мягко говоря плаваю.
0 |
Заблокирован |
||||||||
13.07.2014, 18:01 |
12 |
|||||||
Кстате это расспространенная ошибка, дело в том, что тип <String> Добавлено через 3 минуты
как она должна выглядеть?
Добавлено через 3 минуты
0 |
0 / 0 / 0 Регистрация: 13.07.2014 Сообщений: 16 |
|
13.07.2014, 18:01 [ТС] |
13 |
compile error
0 |
Заблокирован |
||||
13.07.2014, 18:07 |
14 |
|||
Без разницы, можно и так написать
странно что вызвало ошибку, там тоже был допустимый синтакс Добавлено через 2 минуты
x = Towar.Aua?aouYeaiaiouIi?aeaeceoo(«Aaniaie», 1, 0, 0 вообще если разобраться, там еще и ошибки расскладки символов ..
0 |
0 / 0 / 0 Регистрация: 13.07.2014 Сообщений: 16 |
|
13.07.2014, 18:09 [ТС] |
15 |
теперь Syntax error
0 |
Заблокирован |
|
13.07.2014, 18:17 |
16 |
Скорее всего движком форума, ваша кодировка символов расспозналась неверно
0 |
0 / 0 / 0 Регистрация: 13.07.2014 Сообщений: 16 |
|
13.07.2014, 18:18 [ТС] |
17 |
Нет дело в том что и при копировании в блокнот из дебага он русский шрифт переворачивает
0 |
Заблокирован |
|
13.07.2014, 18:24 |
18 |
..Ладно, исправляйте кодировку, у меня тоже был одно время такой глюк..
0 |
maksdemon 0 / 0 / 0 Регистрация: 13.07.2014 Сообщений: 16 |
||||
13.07.2014, 18:25 [ТС] |
19 |
|||
Вот так это выглядет
0 |
Заблокирован |
||||
13.07.2014, 18:31 |
20 |
|||
попробуй теперь, будут ошибки ?
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
13.07.2014, 18:31 |
Помогаю со студенческими работами здесь Если str довольно длинная,то выскакивает ошибка «type mismatch» Почему вдруг начали появляться сообщения «ByRef argument type mismatch»? Ошибка при запуске программы «run time error 13 type mismatch»
Ошибка «argument type mismatch» Function num_cows(s, s1) Ошибка: «Type mismatch» Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 20 |
На чтение 8 мин. Просмотров 27.8k.
Содержание
- Объяснение Type Mismatch Error
- Использование отладчика
- Присвоение строки числу
- Недействительная дата
- Ошибка ячейки
- Неверные данные ячейки
- Имя модуля
- Различные типы объектов
- Коллекция Sheets
- Массивы и диапазоны
- Заключение
Объяснение Type Mismatch Error
Type Mismatch Error VBA возникает при попытке назначить значение между двумя различными типами переменных.
Ошибка отображается как:
run-time error 13 – Type mismatch
Например, если вы пытаетесь поместить текст в целочисленную переменную 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.
- Запустите код, чтобы появилась ошибка.
- Нажмите Debug в диалоговом окне ошибки. Это выделит строку с ошибкой.
- Выберите View-> Watch из меню, если окно просмотра не видно.
- Выделите переменную слева от equals и перетащите ее в окно Watch.
- Выделите все справа от равных и перетащите его в окно 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 — это когда вы читаете из ячейки с ошибкой, например:
Если вы попытаетесь прочитать из этой ячейки, вы получите 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 в коде.
Если мы прочитаем эти данные в числовую переменную, то получим
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 у нас также есть объекты, которые являются более сложными. Примерами являются объекты 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. Есть очень тонкая разница.
- Worksheets — сборник рабочих листов в Workbook
- Sheets — сборник рабочих листов и диаграммных листов в Workbook
Лист диаграммы создается, когда вы перемещаете диаграмму на собственный лист, щелкая правой кнопкой мыши на диаграмме и выбирая «Переместить».
Если вы читаете коллекцию 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. Если у вас есть ошибка несоответствия, которая не раскрыта, пожалуйста, дайте мне знать в комментариях.
В этой статье
- В этой статье
- Поддержка и обратная связь
- Contact Form
- Search This Blog
- Как исправить ошибку во время выполнения 13
- Компания
- Софт
- Ресурсы
- Техподдержка
- Подключить
- How to Fix Type Mismatch (Error 13)
- How to Fix This Error
- Type Mismatch Error with Number
- Runtime Error 6 Overflow
- Clean the Registry
- Scan For Viruses/Malware
- Other Situations When it can Occurs
- Создатели Type mismatch Трудности
- Ошибки во время выполнения в базе знаний
- What Causes Runtime Error 13?
В этой статье
Visual Basic может преобразовать и привести большое число значений для присвоений типа данных, которые не были возможны в предыдущих версиях.
Тем не менее, эта ошибка может по-прежнему повторяться и имеет следующие причины и решения:
- Причина: Переменная или свойство имеют неверный тип. Например, переменная целого типа, не может принимать строковые значения, которые не распознаются как целые числа.
Решение: Попробуйте выполнять задания только между совместимыми типами данных. Например, значение типа Integer всегда можно присвоить типу Long, значение Single — типу Double, а любой тип (за исключением пользовательского) — типу Variant.
- Причина: В процедуру, требующую отдельное свойство или значение, передан объект.
Решение: Передайте отдельное свойство или вызовите метод, соответствующий объекту.
-
Причина: Используется имя модуля или проекта, где требуется выражение, например:
Debug.Print MyModule
Решение: Укажите выражение, которое будет отображаться.
-
Причина: Попытка использовать традиционный механизм обработки ошибок Basic со значениями Variant с подтипом Error (10, vbError), например:
Error CVErr(n)
Решение: Чтобы воссоздать ошибку, необходимо сопоставить ее с пользовательской или внутренней ошибкой Visual Basic, после чего снова создать ее.
-
Причина: Значение CVErr не может быть преобразовано в тип Date. Например:
MyVar = CDate(CVErr(9))
Решение: Используйте оператор Select Case или аналогичную конструкцию, чтобы сопоставить возвращаемое значение CVErr с соответствующим значением.
- Причина: Во время выполнения эта ошибка указывает на то, что переменная Variant, используемая в выражении, имеет неверный подтип, либо переменная Variant, содержащая массив, используется в операторе Print #.
Решение: Для печати массивов используйте цикл в котором каждый элемент отображается отдельно.
Для получения дополнительной информации выберите необходимый элемент и нажмите клавишу F1 (для Windows) или HELP (для Macintosh).
Примечание
Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Тема
- Светлая
- Темная
- Высокая контрастность
- Предыдущие версии
- Блог
- Участие в доработке
- Конфиденциальность и файлы cookie
- Условия использования
- Товарные знаки
- © Microsoft 2022
Contact Form
Name
Email
*
Message
*
<текстареа class=’contact-form-email-message’ cols=’30’ id=’ContactForm1_contact-form-email-message’ name=’email-message’ rows=’15’>
Search This Blog
Как исправить ошибку во время выполнения 13
Рекомендации: Проверьте свой компьютер на наличие ошибок. [Скачать WinThruster — продукт Solvusoft]
Установить необязательные продукты – WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление
Просмотреть ошибки в алфавитном порядке:
# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Компания
Софт
Ресурсы
Техподдержка
Подключить
How to Fix Type Mismatch (Error 13)
The best way to deal with this error is to use to go to the statement to run a specific line of code or show a message box to the user when the error occurs. But you can also check the court step by step before executing it. For this, you need to use VBA’s debug tool, or you can also use the shortcut key F8.
How to Fix This Error
Since most computer users have little to no programming experienced or knowhow, it may appear as though there is nothing that can do about this error. However, if you were to make that assumption, you would be wrong. While the application may be generating a runtime error due to its inability to locate a specific process or file, the reason why this error is occurring, could be due to a bug in the code of the program, file corruption or a bad installation. Developers are constantly releasing updates and patches for their applications, so that’s something you should keep in mind.
Type Mismatch Error with Number
You’re gonna have you can have the same error while dealing with numbers where you get a different value when you trying to specify a number to a variable.
In the following example, you have an error in cell A1 which is supposed to be a numeric value. So when you run the code, VBA shows you the runtime 13 error because it cannot identify the value as a number.
Sub myMacro()
Dim iNum As Long
iNum = Range(“A6”).Value
End Sub
Runtime Error 6 Overflow
In VBA, there are multiple data types to deal with numbers and each of these data types has a range of numbers that you can assign to it. But there is a problem when you specify a number that is out of the range of the data type.
In that case, we will show you runtime error 6 overflow which indicates you need to change the data type and the number you have specified is out of the range.
Clean the Registry
Registry cleaners are very useful tools, as they not only improve the performance of your system, but are also capable of fixing certain errors, such as runtime error 13. If you don’t know what the registry is, it’s basically a database used by your operating system in order to store vital configuration settings. The downside of the registry is that it’s also susceptible to data corruption, which can lead to a plethora of other symptoms, such as system instability, sluggish performance and random errors. Registry cleaners are basically the solution to this problem, as they scan through your systems registry and iron out all of its flaws.
There are many registry cleaner programs out there, but I personally recommend you use Advanced System Repair Pro, which you can download from here:
CLICK HERE TO CHECK OUT ADVANCED SYSTEM REPAIR PRO
Scan For Viruses/Malware
Viruses and malware pose a major problem for the vast majority of computer users out there. Runtime errors are just one of many symptoms of a computer infected with viruses. If a virus or malware gets onto your system, not only will it replicate itself, but it can also corrupt files, some of which may be required for certain applications on your computer to run. Your best option is to ensure that the runtime error 13 you’re receiving isn’t the result of a virus; this can be done by running a full virus scan on your system. I’m assuming you already have antivirus/malware removal software on your computer, but in the event that you do not, I suggest you try out SpyHunter, alternatively you can check out my post on the best antivirus software.
For more information on SpyHunter, visit the following link:
CLICK HERE TO CHECK OUT SPYHUNTER
Other Situations When it can Occurs
There might be some other situations in that you could face the runtime error 14: Type Mismatch.
- When you assign a range to an array but that range only consists of a single cell.
- When you define a variable as an object but by writing the code you specify a different object to that variable.
- When you specify a variable as a worksheet but use sheets collection in the code or vice versa.
Создатели Type mismatch Трудности
Проблемы Type mismatch могут быть отнесены к поврежденным или отсутствующим файлам, содержащим ошибки записям реестра, связанным с Type mismatch, или к вирусам / вредоносному ПО.
В частности, проблемы с Type mismatch, вызванные:
- Поврежденная или недопустимая запись реестра Type mismatch.
- Зазаражение вредоносными программами повредил файл Type mismatch.
- Type mismatch злонамеренно удален (или ошибочно) другим изгоем или действительной программой.
- Другое программное обеспечение, конфликтующее с Windows Operating System, Type mismatch или общими ссылками.
- Поврежденная установка или загрузка Windows Operating System (Type mismatch).
Продукт Solvusoft
WinThruster 2022 – Проверьте свой компьютер на наличие ошибок.
Загрузка
Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11
Установить необязательные продукты – WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление
Ошибки во время выполнения в базе знаний
Идентификатор статьи:
120857
Автор статьи:
Jay Geater
Последнее обновление:
Популярность:
star rating here
Загрузка (Исправление ошибки)
Установить необязательные продукты – WinThruster (Solvusoft)
Лицензия | Политика защиты личных сведений | Условия | Удаление
Tweet
What Causes Runtime Error 13?
The runtime errors occur when an application is running, hence the word “runtime”, this means it will only occur when attempting to run an application or use a specific function within that application. As was mentioned earlier, mismatch errors are typically the catalyst. However, the mismatch within the programs code can be the result of a number of things such as.
- Conflicts Within System Registry
- Malware/Virus Infection
- Microsoft Office Error
- Operating System Requiring An Update
Источники
- https://learn.microsoft.com/ru-ru/office/vba/language/reference/user-interface-help/type-mismatch-error-13
- https://www.excelvbasolutions.com/2020/11/type-mismatch-error-run-time-error-13.html
- https://www.solvusoft.com/ru/errors/%D0%BE%D1%88%D0%B8%D0%B1%D0%BA%D0%B8-%D0%B2%D0%BE-%D0%B2%D1%80%D0%B5%D0%BC%D1%8F-%D0%B2%D1%8B%D0%BF%D0%BE%D0%BB%D0%BD%D0%B5%D0%BD%D0%B8%D1%8F/microsoft-corporation/windows-operating-system/error-13-type-mismatch/
- https://excelchamps.com/vba/type-mismatch-error-13/
- https://www.compuchenna.co.uk/runtime-error-13/
[свернуть]
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. Если у вас есть ошибка несоответствия, которая не раскрыта, пожалуйста, дайте мне знать в комментариях.
7 Ways To Fix Excel Runtime Error 13 Type Mismatch
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.
What Is Runtime Error 13 Type Mismatch?
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:
- Download Excel File Repair Tool rated Excellent by Softpedia, Softonic & CNET.
- Select the corrupt Excel file (XLS, XLSX) & click Repair to initiate the repair process.
- 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:
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 Runtimeerror 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
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”
- Lastly, click on the “Repair” button.
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.
- Here, you will get the list of installed programs on your PC.
- Then from the list select Microsoft Work.
- Click on uninstall to remove it from the PC.
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.
- 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.
- 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.
- 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
- 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.
- 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.
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.
Steps to Resolve Excel Runtime Error 13
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:
- Damaged or incomplete installation of MS Excel application
- The conflict between the Excel application and Operating System
- When a missing menu function or a macro is clicked on by the user from Excel file
- Virus/malware attack or malicious code infection damaging Excel files
- 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:
- Open Excel application
- Go to File->Open
- Select the ‘Excel’ file
- Click the ‘Open’ dropdown
- Click ‘Open and Repair..’ button
- Click ‘Repair’ button to recover as much work as possible Or Click ‘Extract Data’ tab to extract values and formulae
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:
- Go to ‘Task Manager’ and stop the error causing programs one by one
- Click ‘Start’ menu
- Click ‘Control Panel’ button
- Select ‘Add or Remove Program’ or “uninstall a program” option in Control Panel
- All the installed programs on the PC is enlisted
- Select MS Office and click ‘Uninstall’ to remove it from the PC
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 file without hassle. Recovers all important Excel file components: table, chart, chartsheet, formula, cell comment, image, sort, filter, etc. without data loss or change in the structure or formatting of the files. With user-friendly and intuitive interface having easily accessible tabs, buttons, and menus, the Excel repair process is easy and saves time.
About The Author
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 software provid
Stellar Toolkit for File Repair
Microsoft office file repair toolkit to
Stellar Repair for QuickBooks ® Software
The most advanced tool to repair severel
Stellar Repair for Access
Powerful tool, widely trusted by users &
9 comments
Yesterday, I tried to access MS Excel 2016 file but it displays “Excel Runtime Error 13”. To resolve this error I tried manual methods like Open & Repair Utility, Uninstall the error causing program and also used 3rd party free software’s.
But still, I am getting error repeatedly.
Have you tried free demo of Stellar Repair for Excel ?
Its free demo facilitates preview of recoverable Excel data. Then, you would be able to get a better decision.
I have a runtime error 13 type mismatch error on every excel sheet i am trying to use. I just migrated from Windows 10 to a IMAC with El Capitan OSX. I used a easy Bill excel sheet to make bills for my customers, and a bigger sheet for making my daily in and out of cash. The Sheets are working without any problems on windows. Then sent it to the Mac again, but the same problem still occurs.
Has anyone a suggestion?
This problem is associated with an error or damage in an Excel file. So, you can go for professional Excel file repair software.
I keep on receiving the “Runtime Error 13: Type Mismatch whenever I try to use the reshaping tool.
I am happy now with the performance of Excel.
You can share your testimonial with us.
Yesterday, my newly created macro was working fine, but today I always receive the error message:
“Excel VBA Run-time error ’13’ Type mismatch”
How to fix this error?
When inserting / deleting row / rows, get error “Type Mismatch error 13” in Excel. How I can sort out this issue.