Excel VBA: Select Case if ActiveCell like "*string*" -
i'm working on macro takes current value of activecell , changes value based on select case. however, unable determine if activecell contains wild card string. not sure if syntax correct. how can select case compare?
select case activecell.value case activecell.value "*string*" activecell.value = "contains string" end select
it possible use wildcards. keep these 2 things in mind: first, string comparison expressions evaluate boolean data type (true/false); second, per developer reference select...case statement, case expression(s) must "implicitly convertible" same data type of select case test expression. demonstrate, let's use code original post above.
select case activecell.value '-->activecell.value test expression case activecell.value "*string*" '-->(activecell.value "*string*") case expression. activecell.value = "contains string" end select
if selected cell containing string value in worksheet, used immediate window test data type of these 2 expressions using typename() function, following:
?typename(activecell.value) string ?typename(activecell.value "*string*") boolean
as can see, select...case not work here because data types not implicitly same (a minor exception if macro run on cells in worksheet contained single-word values of "true" or "false", excel automatically converts boolean).
the solution simple one. change test expression true.
select case true case (activecell.value "*string*") activecell.value = "contains string" end select
this same writing:
if (activecell.value "*string*") = true activecell.value = "contains string"
it's matter of personal preference whether use if...then or select...case. select...case construct due readability of code, other benefits (such ability pass each case list of expressions separated commas rather using or operator, making code more concise).
Comments
Post a Comment