VBA - Using the Like Operator With Select Case
On June 06,2024 by Tom RoutleyUnder normal circumstances, the
Select Case & Like - Test
The following code demonstrates that Select Case doesn't work with the Like operator:
Sub Select_Case_Like() word = "KAKAO" Select Case word Case mot Like "*K*K*" MsgBox "Good" Case Else MsgBox "Not Good" End Select End Sub
Whatever the content of the word variable, it will always return "not good" ...
Using the True expression -Test
To use the Like operator in a Select Case, you will need to add the True expression.
Sub Select_Case_True_Like() word = "KAO" Select Case True Case word Like "*K*K*" MsgBox "Good" Case Else MsgBox "Not Good" End Select word = "KAKAO" Select Case True Case word Like "*K*K*" MsgBox "Good" Case Else MsgBox "Not Good" End Select End Sub
A useful Boolean function
The function
Function Case_True_Like(word As String) As Boolean Select Case True Case word Like "*K*K*" Case_True_Like = True Case Else Case_True_Like = False End Select End Function
Invoking the function
Sub Test() MsgBox Case_True_Like("KAKAO") End Sub
Conclusion
This article offers an alternative to the use of If ElseIf.
Photo: Unsplash
Article Recommendations
Latest articles
Popular Articles
Archives
- November 2024
- October 2024
- September 2024
- August 2024
- July 2024
- June 2024
- May 2024
- April 2024
- March 2024
- February 2024
- January 2024
- December 2023
- November 2023
- October 2023
- September 2023
- August 2023
- July 2023
- June 2023
- May 2023
- April 2023
- March 2023
- February 2023
- January 2023
- December 2022
- November 2022
- October 2022
- September 2022
- August 2022
- July 2022
- June 2022
- May 2022
- April 2022
- March 2022
- February 2022
- January 2022
- December 2021
- November 2021
- October 2021
- September 2021
- August 2021
- July 2021
- January 2021
Leave a Reply