Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

How to Write Does Not Equal in Excel VBA

· 8 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

You can write does not equal in Excel VBA using the <> operator, which checks if two expressions are not identical. This operator works in If statements, Do While loops, and conditional assignments, making it essential for logic checks where you need to exclude specific values or match criteria. You must use the Application.WorksheetFunction object to call the equivalent NOT function if you need to perform a logical NOT on a cell reference, as the <> symbol cannot be applied directly to a range object in logical expressions.

What You'll Need

  • Microsoft Excel installed on your computer.
  • Basic understanding of VBA: knowing how to open the Visual Basic for Applications Editor and insert a module.
  • Access to Developer Tab: you must have the Developer tab enabled in the ribbon to access the Visual Basic Editor easily.

Step-by-Step

  1. Open the Visual Basic Editor: In Excel, navigate to the Developer tab in the ribbon and click the Visual Basic button. Alternatively, press Alt + F11 on your keyboard to open the editor directly.
  2. Insert a New Module: In the VBA Editor window, right-click on the project name in the Project Explorer pane on the left. Select Insert > Module from the context menu. This creates a new module where you will write your code.
  3. Create a Sub Procedure: In the empty code window of the module, type Sub NotEqualExample() to start a new subroutine. Press Enter to create the structure. You will then type End Sub at the bottom of your code to close the subroutine.
  4. Define Variables: It is good practice to define variables at the start of your procedure to keep your code clean and readable. Type Dim myValue As Variant and press Enter. This variable will hold the value you want to check against another value. You can also define a second variable, such as Dim targetValue As Variant, to store the value you are comparing against.
  5. Assign Values to Variables: Assign some example values to your variables. Type myValue = 10 and press Enter. Then, type targetValue = 20. You are now ready to perform a check to see if these two values are not equal.
  6. Use the Not Equal Operator in an If Statement: Type If myValue <> targetValue Then to begin a conditional block. The <> symbol is the operator for does not equal. Excel VBA will evaluate this condition and execute the code inside the block if the values are different.
  7. Write the Action to Take: Inside the If block, type a message to confirm the condition is met. Type MsgBox "The values are not equal.". This will display a popup dialog box if the check is true.
  8. Handle the Else Condition: To handle the case where the values are equal, type Else on a new line. Then, type MsgBox "The values are equal.". This ensures that a message is displayed regardless of which condition is met.
  9. Close the If Block: Type End If on a new line to close the conditional block.
  10. Run the Macro: Go back to your Excel worksheet. Press Alt + F8 to open the Macro dialog box. Select NotEqualExample from the list and click the Run button. You should see the message box indicating that the values are not equal.
  11. Test with Equal Values: To test the Else condition, modify the code to set both variables to the same value. Change targetValue = 20 to targetValue = 10. Run the macro again. The message box should now display that the values are equal.
  12. Use the Operator in a Loop: The <> operator is also useful in loops. For example, you can use it to skip specific values in a collection. Type Dim i As Integer and i = 1 before your loop. Then, type Do While i <= 10. Inside the loop, type If i <> 5 Then. This ensures that the code inside the loop is skipped when i is 5.
  13. Refine the Loop Logic: Add a line to print the value of i to the Immediate Window by typing Debug.Print i. This will show you which numbers are processed and which are skipped. It is a great way to see the <> operator in action.

Common Mistakes

Confusing the Operator with Text

A common error is using the <> operator on ranges without proper handling. You cannot simply write If Range("A1") <> "Text" Then directly in a logical statement. This will cause a runtime error because VBA cannot compare a range (which can hold many values) to a single string. To fix this, you must first assign the range to a variable using Dim cellValue As Variant. Then, use cellValue = Range("A1").Value. Only then can you perform the comparison: If cellValue <> "Text" Then.

Incorrect Syntax in Loops

When using the <> operator in a Do While loop, ensure that the loop has an exit condition. If you write Do While i <> 100 but never increase the value of i, the loop will run infinitely. Always include a line that increments the counter, such as i = i + 1, inside the loop to prevent this.

Ignoring Data Types

VBA is a loosely typed language, but data types still matter. Comparing a number to a string can lead to unexpected results. For example, 10 <> "10" evaluates to True because one is a number and the other is a string. If you intend to compare values, ensure both are of the same type, either by declaring them as Integer or converting one to the other using CLng or CStr.

Tips

Use the Immediate Window for Debugging

The Immediate Window is a powerful tool for testing VBA code. You can paste your If statements directly into the window to see the results of your logic without running the entire macro. For example, you can type ? 10 <> 20 and press Enter. The window will return True, confirming that the operator works as expected.

Readability is Key

While <> is the standard operator, it can be difficult to read at a glance. For complex conditions, consider using the Not keyword to invert a comparison. For example, instead of If cellValue <> "Empty" Then, you can write If Not cellValue = "Empty" Then. Some developers find this more readable, especially when dealing with multiple And or Or operators.

Check for Nulls

When comparing variables, always check for Null values. A variable that has not been assigned a value is Null, and comparing a Null value to any other value using <> will result in a Null return value, which can break your logic. Use the IsNull function to handle this case: If Not IsNull(cellValue) And cellValue <> "Empty" Then.

Troubleshooting

Runtime Error 13: Type Mismatch

If you encounter a Type Mismatch error, it usually means you are trying to compare a range to a value directly or a string to a number without conversion. Check your code to ensure you have assigned the range to a variable first. If you are comparing a text string to a number, use the CStr function to convert the number to a string or the CLng function to convert the string to a number.

Macro Does Not Run

If the macro does not run, the most common cause is that the macro is not saved in the correct location or is not visible in the Macro dialog box. Ensure that your module is part of the active project in the VBA Editor. If you are using a Personal Macro Workbook, make sure the workbook is open. You can also try saving the workbook as an Excel Macro-Enabled Workbook (.xlsm) to ensure the macros are preserved.

Incorrect Results

If the macro runs but gives the wrong result, check your logic carefully. Use the Debug.Print statement to print the values of your variables to the Immediate Window. This will help you see exactly what values are being compared and why the result might be unexpected.

Frequently Asked Questions

How do I write "does not equal" in a VBA Select Case statement?

You cannot use the <> operator directly in a Select Case statement. Instead, you must use the Case Is keyword. For example, to check if a value is not 10, you would write Select Case myValue, followed by Case Is <> 10. This is the correct syntax for inequality checks within a Select Case block.

Can I use "Does Not Equal" in an Excel formula from VBA?

Yes, you can call standard Excel worksheet functions from VBA. To perform a logical NOT on a cell reference, you would use the Application.WorksheetFunction object. For example, to check if cell A1 is not empty, you would write If Application.WorksheetFunction.CountA(Range("A1")) = 0 Then. This approach is more verbose than using the <> operator directly, but it allows you to use the full power of Excel's worksheet functions in your VBA code.

What is the difference between <> and Not Equals?

In VBA, <> is the symbol for the Not Equal operator, and it is the direct symbol used in code. Not Equals is the English phrase describing what the operator does. There is no separate keyword or function named NotEquals in VBA. You must use the symbol <> or the Not keyword with the = operator to achieve the same result.

How do I handle multiple conditions with "does not equal"?

You can chain multiple conditions using logical operators like And and Or. For example, to check if a value is not 10 and is not 20, you would write If myValue <> 10 And myValue <> 20 Then. This checks both conditions simultaneously and only executes the code block if both are true.

Why does my code skip the loop when it should run?

If your loop skips iterations when it shouldn't, it is likely because the condition is evaluating to False prematurely. Check your counter variables and ensure they are being incremented correctly. Also, verify that your comparison is using the correct data types. For instance, if you are comparing a string that looks like a number to an actual number, the comparison might fail depending on how the data is stored.