如何在excel宏中使用“包含”功能

时间:2016-03-24 23:34:38

标签: excel vba excel-vba macros

我是excel宏的新手。这是我的excel表,有3个输入列,最后一列是输出列,带有我需要的结果。

Excel Input and Output data

以下是我的示例宏:

Function month(x As string, y As string, z As String) As String

If (((x = "January.Winter") Or (y = "January.Winter")) And (z = "jan")) Then
    month= "true"

Else If (((x = "January.2016") Or (y = "January.2016")) And (z = "jan")) Then
    month= "true" 

Else If (((x = "January.today") Or (y = "January.today")) And (z = "jan")) Then
    month= "true"    

Else
    month= False
End If
End Function

我的excel包含数千行,其中包括“january”作为子字符串作为单元格中的文本。而不是像“if”x = January.winter“”那样编写多个检查,我想通过检查字符串“x”或字符串“y”是否包含字符串“January”来简化宏。有没有办法可以改变宏来做到这一点?

感谢。

2 个答案:

答案 0 :(得分:3)

浮现在脑海中的三种方式:

If LCase$(x) Like "january*" Or LCase$(y) Like "january*" Then
    ...


If InStr(LCase$(x), "january") Or InStr(LCase$(x), "january") Then
    ...


If LCase$(Left$(x, 7)) = "january" Or LCase$(Left$(y, 7)) = "january" Then
    ...

这实际上取决于你想要的创造力。

请注意,我已经使用LCase$()强制文字小写并防止出现任何问题 - 在比较字符串时总是值得考虑的事情。

答案 1 :(得分:1)

您可以使用InStr功能。使用示例:

If (InStr(x,"January") > 0 Or InStr(y,"January")>0) And (z = "Jan") Then
 ...

如果找不到子字符串,则返回0,否则返回子字符串的位置。

更多信息here

还要注意上下套管。 " 1"不会匹配" 1月和#34;。使用LCase和UCase函数强制上部或下部外壳,正如Macro Man在他的回答中所做的那样。

相关问题