메모

excel vba case insensitive...펌

맘편한넘 2014. 2. 20. 07:50

Stop Excel VBA Macro Code Being Case Sensitive & Compare Text. Excel VBA Case Sensitive

Got any Excel Questions? Excel Help

Stop Case Sensitivity in Excel VBA Macro Code

By default, Excel VBA code is case sensitive and uses Binary comparisons. This means that "Cat" and "cat" are not seen as being the same. There are many times however, where you like Excel VBA to not use Binary comparisons and have "Cat" = "cat". This can be done in at least 2 ways.

UCASE Function

We can use the Ucase function to ensure all text we compare will be in upper case. Take the example macro below which will show a message box if it encounters any cell in A1:A10 of the active sheet that contains any case variation of the word "CAT".

Sub CompareText()
Dim rCell As Range
    For Each rCell In Range("A1:A10")
        If UCase(rCell) = "CAT" Then
            MsgBox rCell.Address & " has " & rCell & " in it"
        End If
    Next rCell
End Sub

Option Compare Text

The other method we can use will make ALL procedures in a specified Module non-case sensitive. We do this by placing the words Option Compare Text at the very top of the Module we wish to make non-case sensitive. For example, any Procedures placed within the same Module as the Procedure below will no longer be case sensitive. To make ALL procedures within the Module case sensitive again we would replace Option Compare Text with Option Compare Binary

Option Compare Text

Sub OptionCompareText()
Dim rCell As Range
    For Each rCell In Range("A1:A10")
        If rCell = "CAT" Then
            MsgBox rCell.Address & " has " & rCell & " in it"
        End If
    Next rCell
End Sub