Меню

Type mismatch vba excel ошибка runtime 13

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

Mismatch Error

Содержание

  1. Объяснение Type Mismatch Error
  2. Использование отладчика
  3. Присвоение строки числу
  4. Недействительная дата
  5. Ошибка ячейки
  6. Неверные данные ячейки
  7. Имя модуля
  8. Различные типы объектов
  9. Коллекция Sheets
  10. Массивы и диапазоны
  11. Заключение

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

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

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

VBA Type Mismatch Error 13

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

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

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

Sub TypeMismatchStroka()

    ' Объявите переменную типа long integer
    Dim total As Long
    
    ' Назначение строки приведет к Type Mismatch Error
    total = "Иван"
    
End Sub

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

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

Sub TypeMismatchData()

    ' Объявите переменную типа Date
    Dim ReportDate As Date
    
    ' Назначение числа вызывает Type Mismatch Error
    ReportDate = "21-22"
    
End Sub

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

Dim x As Long

' VBA преобразует в целое число 100
x = 99.66

' VBA преобразует в целое число 66
x = "66"

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

Dim x As Long

' Type Mismatch Error
x = "66a"

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

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

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

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

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

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

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

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

VBA Type Mismatch Watch

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

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

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

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

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

Sub TextErrors()

    ' Long - длинное целое число
    Dim l As Long
    l = "a"
    
    ' Double - десятичное число
    Dim d As Double
    d = "a"
    
   ' Валюта - 4-х значное число
    Dim c As Currency
    c = "a"
    
    Dim d As Double
    ' Несоответствие типов, если ячейка содержит текст
    d = Range("A1").Value
    
End Sub

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

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

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

Sub DateMismatch()

    Dim curDate As Date
    
    ' VBA сделает все возможное для вас
    ' - Все они действительны
    curDate = "12/12/2016"
    curDate = "12-12-2016"
    curDate = #12/12/2016#
    curDate = "11/Aug/2016"
    curDate = "11/Augu/2016"
    curDate = "11/Augus/2016"
    curDate = "11/August/2016"
    curDate = "19/11/2016"
    curDate = "11/19/2016"
    curDate = "1/1"
    curDate = "1/2016"
   
    ' Type Mismatch Error
    curDate = "19/19/2016"
    curDate = "19/Au/2016"
    curDate = "19/Augusta/2016"
    curDate = "August"
    curDate = "Какой-то случайный текст"

End Sub

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

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

VBA Runtime Error

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

Dim sText As String

' Type Mismatch Error, если ячейка содержит ошибку
sText = Sheet1.Range("A1").Value

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

Dim sText As String
If IsError(Sheet1.Range("A1").Value) = False Then
    sText = Sheet1.Range("A1").Value
End If

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

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

Function CheckForErrors(rg As Range) As Long

    On Error Resume Next
    CheckForErrors = rg.SpecialCells(xlCellTypeFormulas, xlErrors).Count

End Function

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

Sub DoStuff()

    If CheckForErrors(Sheet1.Range("A1:Z1000")) > 0 Then
        MsgBox "На листе есть ошибки. Пожалуйста, исправьте и запустите макрос снова."
        Exit Sub
    End If
    
    ' Продолжайте здесь, если нет ошибок

End Sub

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

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

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

VBA Error 13

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

Dim rg As Range
Set rg = Sheet1.Range("B2:B5")

Dim cell As Range, Amount As Long
For Each cell In rg
    ' Ошибка при достижении ячейки с текстом «Нет»
    Amount = cell.Value
Next rg

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

Function CheckForTextCells(rg As Range) As Long

    ' Подсчет числовых ячеек
    If rg.Count = rg.SpecialCells(xlCellTypeConstants, xlNumbers).Count Then
        CheckForTextCells = True
    End If
    
End Function

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

Sub IspolzovanieCells()

    If CheckForTextCells(Sheet1.Range("B2:B6").Value) = False Then
        MsgBox "Одна из ячеек не числовая. Пожалуйста, исправьте перед запуском макроса"
        Exit Sub
    End If
    
    ' Продолжайте здесь, если нет ошибок

End Sub

Имя модуля

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

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

Sub IspolzovanieImeniModulya()
    
    ' Type Mismatch Error
    Debug.Print module1

End Sub

VBA Type Mismatch Module Name

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

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

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

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

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

Sub IspolzovanieWorksheet()

    Dim wk As Worksheet
    
    ' действительный
    Set wk = ThisWorkbook.Worksheets(1)
    
    ' Type Mismatch Error
    ' Левая сторона - это worksheet - правая сторона - это workbook
    Set wk = Workbooks(1)

End Sub

Коллекция Sheets

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

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

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

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

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

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

Sub SheetsError()

    Dim sh As Worksheet
    
    For Each sh In ThisWorkbook.Sheets
        Debug.Print sh.Name
    Next sh

End Sub

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

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

Sub IspolzovanieMassiva()

    Dim arr As Variant
    
    ' Присвойте диапазон массиву
    arr = Sheet1.Range("A1:B2").Value
    
    ' Выведите значение в строку 1, столбец 1
    Debug.Print arr(1, 1)

End Sub

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

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

Sub OshibkaIspolzovanieMassiva()

    Dim arr As Variant
    
    ' Присвойте диапазон массиву
    arr = Sheet1.Range("A1").Value
    
    ' Здесь будет происходить Type Mismatch Error
    Debug.Print arr(1, 1)

End Sub

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

Sub IspolzovanieMassivaIf()

    Dim arr As Variant
    
    ' Присвойте диапазон массиву
    arr = Sheet1.Range("A1").Value
    
    ' Здесь будет происходить Type Mismatch Error
    If IsArray(arr) Then
        Debug.Print arr(1, 1)
    Else
        Debug.Print arr
    End If

End Sub

Заключение

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

Summary:

This post is written with the main prospective of providing you all with ample amount of detail regarding Excel runtime error 13.  So go through this complete guide to know how to fix runtime error 13 type mismatch.

In our earlier blogs, we have described the commonly found Excel file runtime error 1004, 32809 and 57121. Today in this article we are describing another Excel file runtime error 13.

Run-time error ‘13’: Type Mismatch usually occurs meanwhile the code is executed in Excel. As a result of this, you may get terminated every time from all the ongoing activities on your Excel application.

This run time error 13 also put an adverse effect on XLS/XLSX files. So before this Excel Type Mismatch error damages your Excel files, fix it out immediately with the given fixes.

Apart from that, there are many reasons behind getting the Excel file runtime error 13 when the Excel file gets corrupted this starts showing runtime error.

To recover lost Excel data, we recommend this tool:

This software will prevent Excel workbook data such as BI data, financial reports & other analytical information from corruption and data loss. With this software you can rebuild corrupt Excel files and restore every single visual representation & dataset to its original, intact state in 3 easy steps:

  1. Download Excel File Repair Tool rated Excellent by Softpedia, Softonic & CNET.
  2. Select the corrupt Excel file (XLS, XLSX) & click Repair to initiate the repair process.
  3. Preview the repaired files and click Save File to save the files at desired location.

Error Detail:

Error code: Run-time error ‘13’

Declaration: Excel Type Mismatch error

Here is the screenshot of this error:

Excel Runtime Error 13 Type Mismatch

Why Am I Getting Excel Runtime Error 13 Type Mismatch?

Following are some reasons for run time error 13 type mismatch:

  • When multiple methods or files require to starts a program that uses Visual Basic (VB) environment
  • Runtime error 13 often occurs when mismatches occur within the software applications which you require to use.
  • Due to virus and malware infection as this corrupts the Windows system files or Excel-related files.
  • When you tap on the function or macro present on the menu which is created by another Macro then also you will receive the same run time error 13.
  • The runtime error commonly occurs due to the conflict between the software and the operating system.
  • Due to the corrupt or incomplete installation of Microsoft Excel software.
  • The Run-time Error 13 appears when the users try to run VBA code that includes data types that are not matched correctly. Thus it starts displaying Runtime error 13 type mismatch.
  • Due to conflict with other programs while opening the VBA Excel file.

Well, these are some of the common reasons for getting the Excel file runtime error 13.

How To Fix Excel Runtime Error 13 Type Mismatch?

Learn how to Fix Excel Runtime Error 13 Type Mismatch.

1: Using Open and Repair Utility

2. Uninstall The Program

3. Scan For Virus/Malware

4. Recover Missing Macros

5.  Run The ‘Regedit’ Command In CMD

6: Create New Disk Partition And Reinstall Windows

7: Use MS Excel Repair Tool

1: Using Open and Repair Utility

There is a ‘File Recovery’ mode within Excel which gets activated automatically when any corruption issue hits your worksheet or workbook.

But in some cases, Excel won’t offer this ‘File Recovery’ mode and at that time you need to use Excel inbuilt tool ‘Open and Repair’.

Using this inbuilt utility tool you can recover corrupted/damaged Excel files. Try the following steps to fix Visual Basic runtime error 13 type mismatch in Excel.

Here follow the steps to do so:

  • In the File menu> click “Open”
  • And select corrupt Excel file > from the drop-down list of open tab > select “Open and Repair”

Open-and-Repair

  • Lastly, click on the “Repair” button.

excel open and repair

However, it is found that the inbuilt repair utility fails to repair the severely damaged Excel file.

2. Uninstall The Program

It is found some application and software causes the runtime error.

So, to fix the Excel file error, simply uninstall the problematic apps and programs.

  • First, go to the Task Manager and stop the running programs.
  • Then in the start menu > select Control Panel.
  • In the Control Panel > choose Add or Remove Program.

Reinstall The Microsoft Office Application

  • Here, you will get the list of installed programs on your PC.

ms office repair from control panel

  • Then from the list select Microsoft Work.
  • Click on uninstall to remove it from the PC.

Uninstall The Program

Hope doing this will fix the Excel file Runtime error 13, but if not then follow the third solution.

3. Scan For Virus/Malware

Virus intrusion is quite a big problem for all Windows users, as it causes several issues for PC and Excel files.

This can be the great reason behind this Runtime 13 error. As viruses damage the core program file of MS Office which is important for the execution of Excel application.

This makes the file unreadable and starts generating the following error message: Visual Basic runtime error 13 type mismatch in Excel

To avoid this error, you need to remove all virus infections from your system using the reliable anti-virus removal tool.

Well, it is found that if your Windows operating system in having viruses and malware then this might corrupt Excel file and as a result, you start facing the runtime file error 13.

So, it is recommended to scan your system with the best antivirus program and make your system malware-free. Ultimately this will also fix runtime error 13.

4. Recover Missing Macros

Well, as it is found that users are getting the runtime error 13 due to the missing macros, So try to recover the missing Macros.

Here follow the steps to do so:

  • Open the new Excel file > and set the calculation mode to Manual
  • Now from the Tools menu select Macro > select Security > High option.
  • If you are using Excel 2007, then click the Office button > Excel Options > Trust Center in the left panel
  • And click on Trust Center Settings button > Macro Settings > Disable All Macros without Notification in the Macro Settings section > click OK twice.

enable excel macros 1

  • Now, open the corrupted workbook. If Excel opens the workbook a message appears that the macros are disabled.
  • But if in case Excel shut down, then this method is not workable.
  • Next press [Alt] + [F11] for opening the Visual Basic Editor (VBE).
  • Make use of the Project Explorer (press [Ctrl]+R) > right-click a module > Export File.

Copy Macros in the Personal Macro Workbook 3

  • Type name and folder for the module > and repeat this step as many times as required to export the entire module.
  • Finally, close the VBE and exit.

Now open the new blank workbook (or the recently constructed workbook that contains recovered data from the corrupted workbook) and import the modules.

5.  Run The ‘Regedit’ Command In CMD

This Excel error 13 can also be fixed by running the ‘Regedit’ command in the command prompt.

  • In the search menu of your system’s start menu type run command.
  • Now in the opened run dialog box type “regedit” command. After that hit the OK
  • This will open the registry editor. On its right side there is a ‘LoadApplnit_DLLs value.’ option, just make double-tap to it.
  • Change the value from 1 to ‘0‘and then press the OK.

Run The ‘Regedit’ Command In CMD

  • Now take exit from this opened registry editor.
  • After completing all this, restart your PC.

Making the above changes will definitely resolve the Runtime Error 13 Type Mismatch.

6: Create New Disk Partition And Reinstall Windows 

If even after trying all the above-given fixes Excel type mismatched error still persists. In that case, the last option left here is to create the new partition and reinstall Windows.

  • In your PC insert windows DVD/CD and after that begin the installation procedure.
  • For installation, choose the language preference.
  • Tap to the option” I accept” and then hit the NEXT
  • Select the custom advance option and then choose the  Disk O partition 1

Create New Disk Partition And Reinstall Windows 

  • Now hit the delete> OK button.
  • The same thing you have to repeat after selecting the Disk O partition 2.
  • Now hit the delete> OK button to delete this too.
  • After completing the deletion procedure, tap to create a new partition.
  • Assign the disk size and tap to the Apply.

Create New Disk Partition And Reinstall Windows  1

  • Now choose the Disk 0 partition 2 and then hit the Formatting.
  • After complete formatting, hit the NEXT button to continue.

Note: before attempting this procedure don’t forget to keep a complete backup of all your data.

However, if you are still facing the Excel Runtime file error 13 then make use of the third party automatic repair tool.

7: Use MS Excel Repair Tool

It is recommended to make use of the MS Excel Repair Tool. This is the best tool to repair all sort of issues, corruption, errors in Excel workbooks. This tool allows to easily restore all corrupt excel file including the charts, worksheet properties cell comments, and other important data.

* Free version of the product only previews recoverable data.

This is a unique tool to repair multiple excel files at one repair cycle and recovers the entire data in a preferred location. It is easy to use and compatible with both Windows as well as Mac operating systems.

Steps to Utilize MS Excel Repair Tool:

Final Verdict:

After reading the complete post you must have got enough idea on Visual Basic runtime error 13 type mismatch in Excel. Following the listed given fixes you are able to fix the Excel runtime file error 13.

I tried my best to provide ample information about the runtime error and possible workarounds that will help you to fix the Excel file error.

So, just make use of the solutions given and check whether the Excel error is fixed or not.

In case you have any additional workarounds that proved successful or questions concerning the ones presented, do tell us in the comments.

Hope you find this post informative and helpful.

Thanks for reading…!

Summary

5 Ways To Fix Excel Runtime Error 13 Type Mismatch

Article Name

5 Ways To Fix Excel Runtime Error 13 Type Mismatch

Description

Read the complete guide to know how to fix Excel runtime error 13 type mismatch. Also know the exact reason behind this error.

Author

Publisher Name

Repair MS Excel Blogs

Publisher Logo

Repair MS Excel Blogs

Priyanka Sahu

Priyanka is an entrepreneur & content marketing expert. She writes tech blogs and has expertise in MS Office, Excel, and other tech subjects. Her distinctive art of presenting tech information in the easy-to-understand language is very impressive. When not writing, she loves unplanned travels.

Home / VBA / VBA Type Mismatch Error (Error 13)

Type Mismatch (Error 13) occurs when you try to specify a value to a variable that doesn’t match with its data type. In VBA, when you declare a variable you need to define its data type, and when you specify a value that is different from that data type you get the type mismatch error 13.

In this tutorial, we will see what the possible situations are where runtime error 13 can occurs while executing a code.

Type Mismatch Error with Date

In VBA, there is a specific data type to deal with dates and sometimes it happens when you using a variable to store a date and somehow the value you specify is different.

In the following code, I have declared a variable as the date and then I have specified the value from cell A1 where I am supposed to have a date only. But as you can see the date that I have in cell one is not in the correct format VBA is not able to identify it as a date.

Sub myMacro()
Dim iVal As Date
iVal = Range("A1").Value
End Sub

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.

Other Situations When it can Occurs

There might be some other situations in that you could face the runtime error 14: Type Mismatch.

  1. When you assign a range to an array but that range only consists of a single cell.
  2. When you define a variable as an object but by writing the code you specify a different object to that variable.
  3. When you specify a variable as a worksheet but use sheets collection in the code or vice versa.

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.

There’s More VBA Errors

Subscript Out of Range (Error 9) | Runtime (Error 1004) | Object Required (Error 424) | Out of Memory (Error 7) | Object Doesn’t Support this Property or Method (Error 438) | Invalid Procedure Call Or Argument (Error 5) | Overflow (Error 6) | Automation error (Error 440) | VBA Error 400

Make sure to check out this VBA Error Handling technique and if you want to learn more don’t forget to jump to this VBA Tutorial.

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

Free Download for Windows

Contents

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

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

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

Excel Runtime Error 13

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

Causes for Excel Runtime Error 13

The Excel runtime error 13 causes are as follows:

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

Fixes

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

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

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

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

Stellar

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

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

Fix 2: Uninstall the ‘error causing program’

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

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

Image of Control Panel > Programs

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

Image of Microsoft Office being uninstalled from Control Panel

Limitations

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

Fix 3: Use Stellar Repair for Excel

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

Free download

Conclusion

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

About The Author

Priyanka

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

Best Selling Products


Stellar Repair for Excel

Stellar Repair for Excel

Stellar Repair for Excel software provid

Read More


Stellar Toolkit for File Repair

Stellar Toolkit for File Repair

Microsoft office file repair toolkit to

Read More


Stellar Repair for QuickBooks ® Software

Stellar Repair for QuickBooks ® Software

The most advanced tool to repair severel

Read More


Stellar Repair for Access

Stellar Repair for Access

Powerful tool, widely trusted by users &

Read More

Содержание

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

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

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

Обзор «Type mismatch»

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Имя модуля

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

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

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

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

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

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

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

Коллекция Sheets

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

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

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

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

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

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

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

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

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

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

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

Заключение

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

Источник

In this Article

  • VBA Type Mismatch Errors
    • What is a Type Mismatch Error?
    • Mismatch Error Caused by Worksheet Calculation
      • Mismatch Error Caused by Entered Cell Values
      • Mismatch Error Caused by Calling a Function or Sub Routine Using Parameters
      • Mismatch Error Caused by using Conversion Functions in VBA Incorrectly
      • General Prevention of Mismatch Errors
      • Define your variables as Variant Type
      • Use the OnError Command to Handle Errors
      • Use the OnError Command to Supress Errors
      • Converting the Data to a Data Type to Match the Declaration
      • Testing Variables Within Your Code
      • Objects and Mismatch Errors

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:

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!

automacro

Learn More

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

 

Дмитрий Марков

Пользователь

Сообщений: 140
Регистрация: 24.02.2015

#1

22.01.2021 11:32:25

Добрый день,

При получении в массив единственного элемента, вход в цикл For each возвращает ошибку Run-time error ’13’: Type mismatch
Если в массиве два и более элементов, цикл отрабатывает

Код
    Dim ВыкладкаФайлы As Variant
           
Sheets("Генератор").Select
          
lLastRow = Sheets("Генератор").Cells(Rows.Count, 19).End(xlUp).Row
Sheets("Генератор").Range(Cells(1, 19), Cells(lLastRow, 19)).Select
ВыкладкаФайлы = Selection.Value2

For Each Filename In ВыкладкаФайлы ' здесь Run-time error '13': Type mismatch
Debug.Print Filename
 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

For Each работает с коллекцией или массивом
Dim ВыкладкаФайлы As Variant — и где здесь видно, что это? Да, какая-то переменная, подходит и для значения, и для массива…

Выделили (выделять не обязательно) одну ячейку, получили: ВыкладкаФайлы — обычная переменная , в которой хранится значение.

 

Здравствуйте, vikttur,

Dim ВыкладкаФайлы() As Variant ? (если я правильно понял)

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

Для массива — да.
Но получите ошибку при заполнении массива одним значением :)

 

Но как же этого можно избежать? ))

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

Не входить в цикл, если один элемент.
Можно в массив взять два столбца, но обрабатывать только первый (For i = 1 To UBound(массив)). Медленнее и лишнюю память откусит.

 

Дело в том, что у меня там несколько последовательно вложенных друг в друга циклов
(разбивка списка по критерию / разбивка категории на примерно равные части / формирование содержимого нового файла / …)
и когда категория состоит из единственной части, мне не очень понятно как корректно прописать обход цикла – буду благодарен за помощь

т.е. от количества уровней вложенности голова уже прилично кружится)

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#8

22.01.2021 12:26:19

Цитата
Дмитрий Марков написал: прописать обход цикла
Код
If  lLastRow >1 Then
    цикл
Else
    не цикл
End If

Цитата
от количества уровней вложенности голова уже прилично кружится

Это головокружение от счастья («все мои!!!») :)
Если вложенных циклов много — поора думать об оптимизации.

 

V

Пользователь

Сообщений: 4999
Регистрация: 22.12.2012

#9

22.01.2021 12:26:27

Цитата
Дмитрий Марков написал:
как корректно прописать обход цикла

вариант

Код
if lLastRow=1 Then
без цикла
ELSE
цикл
end if 

Изменено: V22.01.2021 12:27:34

 

Дмитрий Марков

Пользователь

Сообщений: 140
Регистрация: 24.02.2015

#10

22.01.2021 12:29:09

Цитата
vikttur написал:
Если вложенных циклов много — пора думать об оптимизации.

Но ведь это уже совсем другой уровень! Холмс!

 
 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 13958
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#12

22.01.2021 12:49:27

Ну вообще все делается иначе обычно.

Код
Dim ВыкладкаФайлы
ВыкладкаФайлы = Selection.Value2
If Not IsArray(ВыкладкаФайлы) Then
    ReDim ВыкладкаФайлы(1 to 1, 1 to 1)
    ВыкладкаФайлы(1,1) = Selection.Value2
end if

а далее работаем с массивом и все.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

RAN

Пользователь

Сообщений: 7081
Регистрация: 21.12.2012

#13

22.01.2021 12:50:44

Цитата
vikttur написал:
Но получите ошибку при заполнении массива одним значением

Не пудри мозги!  :)
При заполнении массива 1 значением ошибки не будет.
А при заполнении с листа, при условии, что в диапазоне 1 ячейка, массива не будет.

 

Дмитрий Марков

Пользователь

Сообщений: 140
Регистрация: 24.02.2015

#14

22.01.2021 12:59:04

Дмитрий(The_Prist) Щербаков, большое спасибо!

Цитата
RAN написал: А при заполнении с листа, при условии, что в диапазоне 1 ячейка, массива не будет

RAN, в том-то и дело, что заполнение происходит с листа, а массив () – всепогодный, если верно понимаю

 

Jack Famous

Пользователь

Сообщений: 10382
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#15

22.01.2021 13:00:14

Дмитрий(The_Prist) Щербаков, приветствую, Дим!

Добавлю, что можно подсократить и ускорить для циклов:

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#16

22.01.2021 13:36:30

Цитата
RAN написал: Не пудри мозги!

Котелком прикрылся. Тебе запудришь…  :)
За уточнение спасибо. Я написал только применительно к конкретному случаю.

Цитата
RAN написал: А при заполнении с листа, при условии, что в диапазоне 1 ячейка, массива не будет.

Массив объявленный останется. Ошибка будет :)

Код
Sub Test_()
    Dim a()
    
    a = Range("A1").Value
End Sub
 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 13958
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#17

22.01.2021 14:07:27

Цитата
Jack Famous написал:
можно подсократить и ускорить для циклов

ускорения тут не вижу, если честно…Сокращение строк — да. Но я этим не страдаю :)
И там и там инициализация массива займет одинаковое кол-во времени(у меня через ReDim, у тебя через Dim). Только в моем коде этой инициализации не будет, если выделено более одной ячейки. Да, есть однозначное присвоение значения переменной, но оно есть и у тебя.
Плюс, в твоем коде идет сначала получение значений из ячеек, а потом перекидывание этих значений из одного массива в другой(одного значения). Не уверен, что такой подход что-то ускорит.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

RAN

Пользователь

Сообщений: 7081
Регистрация: 21.12.2012

#18

22.01.2021 14:17:46

Нужно мяукнуть, и будет вам массив из одной ячейки.

Код
Sub мяу()
    Dim ar
    ar = Selection.Value
    If Not IsArray(ar) Then
        ReDim ar(1 To 1, 1 To 1)
        ar(1, 1) = Selection.Value
    End If
End Sub

PS Когда писал, сообщения 12 не видел.  :)

Изменено: RAN22.01.2021 14:36:09

 

Jack Famous

Пользователь

Сообщений: 10382
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#19

22.01.2021 14:29:12

Цитата
Дмитрий(The_Prist) Щербаков: ускорения тут не вижу, если честно

А так?

инициация у меня 1 раз, а у тебя будет [переопределение] (для этого примера) — для каждой области, состоящей из одной ячейки ;)

Изменено: Jack Famous22.01.2021 15:28:19
(Добавил указание про переопределение)

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 13958
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#20

22.01.2021 15:19:33

Цитата
Jack Famous написал:
у тебя будет (для этого примера) — для каждой области

не, ну если таким путем идти, то конечно. Только ты забываешь и еще одну вещь: переопределение через ReDim не одно и тоже, что инициализация :) И происходит быстрее, т.к. сам массив по сути уже есть.
Если бы мне было не лень — может сделал бы сравнительный анализ. Но что-то подсказывает, что выигрыша в скорости в твоем варианте ожидать особо не стоит. Потому что переопределение массива явно быстрее, чем пихание сначала в заранее определенный массив одной ячейки, а потом пихание его в другой массив, который на лету должен будет все равно переопределиться(внутренними ресурсами). Т.е. по сути тот же ReDim все равно будет вызван…Могу ошибаться, конечно, но что-то такое в памяти всплывает из области назначения значений массиву на лету.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Jack Famous

Пользователь

Сообщений: 10382
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#21

22.01.2021 15:27:15

Цитата
Дмитрий(The_Prist) Щербаков: переопределение массива явно быстрее, чем пихание

ща проверю и отпишусь в этот пост  :)

250 против 270 мс. Мои 2 строчки быстрее — незначительно, но стабильно

не знаю, как там технически, но переопределять что-то мне кажется более долгим, чем присваивать в готовое

Изменено: Jack Famous22.01.2021 15:37:28

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 13958
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#22

22.01.2021 16:51:40

Цитата
Jack Famous написал:
переопределять что-то мне кажется более долгим, чем присваивать в готовое

тут как бы…Да, в данном конкретном случае, скорее всего так и есть. Ибо значений мало. Но если речь не про одну ячейку — то все же нет.
А в данном конкретном случае таки да — твой вариант выигрывает по скорости. Но использовать я все равно буду свой  8)  

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Jack Famous

Пользователь

Сообщений: 10382
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#23

22.01.2021 17:30:45

Цитата
Дмитрий(The_Prist) Щербаков: значений мало. Но если речь не про одну ячейку — то все же нет

так в примере же цикл на  млн — как одно-то?)))

Цитата
Дмитрий(The_Prist) Щербаков: использовать я все равно буду свой

разница в рамках погрешности, так что вообще ничего не потеряешь  :)

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 13958
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#24

22.01.2021 20:43:18

Цитата
Jack Famous написал:
так в примере же цикл на  млн — как одно-то?)

о нет, я не про то. Я про то, что если в массив загонять не одну ячейку, а куда больше :)

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Дмитрий Марков

Пользователь

Сообщений: 140
Регистрация: 24.02.2015

#25

23.01.2021 00:59:39

Цитата
Дмитрий(The_Prist) Щербаков написал: Ну вообще все делается иначе…  работаем с массивом и все

Дмитрий, в код очень удачно зашла Ваша конструкция, в основном потому, что на месте ‘выворачивает’) переменную в массив

Большое спасибо всем-всем, за направление, помощь, и конструктив) Всех благ!  

Type mismatch error, or we can also call it Error code 13, occurs when we assign a value to a variable that is not of its data type. For example, if we provide a decimal or long value to an Integer data type variable, we will encounter this Type mismatch error when we run the code, which shows as error code 13.

VBA Type Mismatch Error in excel is a type of “Run Time Error,” and it is the number 13 error in this category.

To start learning in VBA and for beginners, it is hard to find the error thrown by the VBA codes. Remember, VBA is not throwing an error. Rather, it is just highlighting our mistakes while writing the code.

We usually declare variables. We assign data types to them. When we assign a value to those variables, we need to remember what kind of data it can hold. If the assigned value is not as per the data type, we will get “Run-time error ’13’: Type mismatch.”

Table of contents
  • What is VBA Type Mismatch Error?
    • How to Fix VBA Type Mismatch Run-time Error 13?
      • VBA Type Mismatch – Example #1
      • VBA Type Mismatch – Example #2
      • VBA Type Mismatch – Example #3
      • VBA Type Mismatch – Example #4
    • Recommended Articles

VBA Type Mismatch Error

You are free to use this image on you website, templates, etc., Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Type Mismatch Error (wallstreetmojo.com)

How to Fix VBA Type Mismatch Run-time Error 13?

Let us see some examples to understand this VBA Type Mismatch Error.

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

VBA Type Mismatch – Example #1

Look at the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

Code:

Sub Type_MisMatch_Example1()

Dim k As Byte

k = "Hiii"

MsgBox k

End Sub

vba mismatch example 1.1

We have declared the variable “k” as Byte.

The variable “k” can hold values from 0 to 255. But in the next line, we have assigned the value for the variable “k” as “Hiii.”

The data type cannot hold a text’s value, so the Type Mismatch Error comes.

vba mismatch example 1.2

VBA Type Mismatch – Example #2

Now, look at one more example with a different data type. Look at the below code.

Code:

Sub Type_MisMatch_Example2()

Dim x As Boolean

x = 4556

MsgBox x

End Sub

vba mismatch example 2.1

We have declared the variable “x” as Boolean.

Boolean is a data typeBoolean is an inbuilt data type in VBA used for logical references or logical variables. The value this data type holds is either TRUE or FALSE and is used for logical comparison. The declaration of this data type is similar to all the other data types.read more that can hold the value of either TRUE or FALSE.

In the above code, we have assigned a value of 4556, which is not as per the data type values of TRUE or FALSE.

When we run this code, you would expect a type mismatch error, but see what happens when we run this code.

vba mismatch example 2.2

You must wonder why this is not “Run-time error ’13’ ” or a type mismatch.

The reason for this is excel treats all the numbers as TRUE except zero. So, zero value will be treated as FALSE. So that is why we got the result as TRUE instead of an error.

Now see, we will assign a numerical value with text.

Code:

Sub Type_MisMatch_Example2()

Dim x As Boolean

x = "4556a"

MsgBox x

End Sub

vba mismatch example 2.3

It will throw “Run-time error ’13’: Type mismatch.”

vba mismatch example 2.4

VBA Type Mismatch – Example #3

Now, look at the below code for this example.

Code:

Sub Type_MisMatch_Example4()

Dim x As Integer
Dim y As String

x = 45
y = "2019 Jan"

MsgBox x + y

End Sub

example 3.1

Variable “x” is an Integer data type, and “y” is a String data type.

X = 45 and y = 2019 Jan.

In the message box, we have added x + y.

But this is not the perfect code because we cannot add numbers with string texts. As a result, we will encounter “Run-time error ’13.’ “

example 3.2

VBA Type Mismatch – Example #4

Exceptional Cases

There are situations where excel forgives the erroneous data assigned to the variable data type. For example, look at the below code.

Code:

Sub Type_MisMatch_Example3()

Dim x As Long
Dim y As Long

x = 58.85

y = "85"

MsgBox x & vbNewLine & y

End Sub

example 4.1

Two declared variables are “x” and “y.”

For this variable, the assigned data type is “Long.”

The long data type accepts only whole numbers, not decimal values.

So, the general perception is to get “Run-time error 13′ ” of type mismatch error.

But let us see what happens when we run this code

example 4.2

We got the values 59 and 85.

VBA will convert the decimal value 58.85 to the nearest integer value. Even though numbers enclosed with double quotes, it only converts to the integer value.

Recommended Articles

This article has been a guide to VBA Type Mismatch. Here, we discussed VBA Type Mismatch “Run-time error ’13’ ‘ in VBA with examples and a downloadable Excel template. Below are some useful articles related to VBA: –

  • Data Type in Excel VBA
  • What is Type Statement in Excel VBA?
  • What is the Integer Data Type?
  • VBA Select Case

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Txd workshop ошибка при открытии hud txd для gta sa
  • Tx800fw epson ошибка принтера