In this session, we delve into the String Compare function in VBA. This function allows users to compare two strings and determine whether they are equal, greater, or lesser. By treating strings as numerical values, particularly emphasizing the differences between uppercase and lowercase letters, the String Compare function offers essential text manipulation capabilities for Excel users. We explore both default binary comparison and text comparison through practical examples to understand the function's behavior comprehensively.

What will you learn

  • How to use the String Compare function in VBA.
  • The difference between binary and text comparisons.
  • How VBA views strings as numerical values.
  • The significance of uppercase and lowercase letters in string comparisons.
  • Practical implementation through example scenarios.

Takeaway notes

  • The String Compare function in VBA is used by writing STICOMT followed by two strings, with an optional comparison type.
  • Comparison types: 0 for binary comparison (default) and 1 for text comparison.
  • Strings are treated as numerical values by VBA, impacting how comparisons are executed.
  • In a binary comparison, capital letters are deemed lesser than lowercase letters.
  • In text comparison, the function disregards case differences.
  • Exact matches return 0, whereas non-matches return 1 or -1 depending on the comparison logic and order.

Practice questions

  1. Write a VBA code snippet that compares the strings "Excel" and "excel" using binary comparison.
  2. Compare the strings "Data" and "DATA" using text comparison in VBA. What result do you get?
  3. Explain why the result of comparing "Hello" and "hello" is different in binary and text comparisons.
  4. How would you modify the String Compare function to compare "123" and "1234" in VBA?
  5. Provide an example where a binary comparison would return 1.
  6. In which scenario would a text comparison return 0 while a binary comparison would return 1?
  7. Write a VBA subroutine that compares the strings "Board" and "Inifinty" and outputs whether one is greater than the other.
  8. What does the String Compare function return when comparing two completely different strings like "apple" and "orange"?
  9. If you input "alpha" and "ALPHA" in a binary comparison, what will the result be?
  10. Create a VBA function that compares two user-input strings and displays an appropriate message.
  11. Explain how numerical values are assigned to characters during a string comparison in VBA.
  12. Why might you choose to use a text comparison over a binary comparison in a specific Excel task?
  13. Compare "String1" and "String2" using text comparison. What will the result signify?
  14. How can the String Compare function be useful in sorting a list of words in VBA?
  15. Demonstrate a scenario where adding white spaces in one of the strings affects the comparison result.

Mark Lesson Complete (Mastering String Comparisons in VBA)