Type Mismatch VBA
When we try to assign a value between two different variable types, then an error occurs that is called the VBA Type Mismatch error.
This error occurs during the run time, such as “run-time error 13: Type mismatch”.
For example: If we provide a text value to an integer data type variable, then the Type mismatch error occurs during the execution time of the code.
We declare the variables in the code and assign the data types to it. We need to remember during providing the value to those variables that what kind of data it holds. If the provided value is not as per the data type requirement, then it throws the “Run Time Error 13: Type Mismatch” error.
Advantages of VBA Type Mismatch
Below are some advantages of the Type mismatch error, such as:
- We know the actual mistake where it happened in the code.
- Without the compilation of the code, we can get the point of error in the code.
Examples
Here are some steps to show the type mismatch error. Now, follow the following steps, such as:
Step 1: Click on the Developer tab.
Step 2: And click on the Visual Basic option.
Step 3: Then click on the Insert button on the pop-up window.
Step 4: Now insert a new Module.
Step 5: Double click on the newly added Module; it opens a code window.
Step 6: Write a VBA code on the code window.
Step 7: Next, define a variable “X” as an Integer data type.
Step 8: Integer data type can store numbers and whole numbers only. But we assign a text value to the X variable.
Step 9: We use the Message box to see the stored values in the X variable.
Step 10: Execute the above code by clicking the Run button.
After execution, it displays an error message “Run-time error ’13’: Type Mismatch”. The integer data type can only store the Numbers or Whole Numbers, but we assign the text value to the integer data type. That’s why it gives an error.
If we assign the right value to the variable, we will get the correct output, as shown below:
Now execute the above code, it will give the correct output without showing any error.
Example 2: Here is another example with the different data type, such as:
We define the variable “A” as Boolean. The Boolean data type can hold either True or False value only.
We assign the value 100, but it is not as per the data type value.
Now execute the above code by clicking the Run button.
After execution of the above code, it does not display any error message because excel treats all the numbers as True except zero, and zero is treated as False.
If we add a text value with the numeric value, then it displays an error, such as:
Again execute the same code, now it will display the error as shown in the below screenshot, such as: