Excel VBA如果单元格.Value=。。。然后

Excel VBA如果单元格.Value=。。。然后,vba,excel,Vba,Excel,我有这样一个代码,它工作得很好: Sub colortest() Dim cell As Range For Each cell In Range("Range1") If cell.Value = "Word1" Then cell.Interior.Color = XlRgbColor.rgbLightGreen ElseIf cell.Value = "Word2" Then cell.Interior.Color = XlRgbColor.rgbOrange ElseIf cell.Va

我有这样一个代码,它工作得很好:

Sub colortest()
Dim cell As Range
For Each cell In Range("Range1")
If cell.Value = "Word1" Then
cell.Interior.Color = XlRgbColor.rgbLightGreen
ElseIf cell.Value = "Word2" Then
cell.Interior.Color = XlRgbColor.rgbOrange
ElseIf cell.Value = "Word3" Then
cell.Interior.Color = XlRgbColor.rgbRed
End If
Next cell
End Sub
我的问题是,只有当单元格仅包含该文本时,值才起作用。但我的细胞通常是这样的:“某物,10254,15/15,Word1另一个单词” 我只需要单词1
谢谢,

您可以使用

If InStr(cell.Value, "Word1") > 0 Then

如果在字符串中找到Word1,
InStr()
函数将返回字符串中Word1的第一个字符的位置。

我认为在Excel中使用“Find”函数而不是每个循环更有意义。它的工作速度要快得多,而且是专为这种行为设计的。试试这个:

 Sub FindSomeCells(strSearchQuery As String)   

    Set SearchRange = Worksheets("Sheet1").Range("A1:A100")
    FindWhat = strSearchQuery
    Set FoundCells = FindAll(SearchRange:=SearchRange, _
                            FindWhat:=FindWhat, _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByColumns, _
                            MatchCase:=False, _
                            BeginsWith:=vbNullString, _
                            EndsWith:=vbNullString, _
                            BeginEndCompare:=vbTextCompare)
    If FoundCells Is Nothing Then
        Debug.Print "Value Not Found"
    Else
        For Each FoundCell In FoundCells
            FoundCell.Interior.Color = XlRgbColor.rgbLightGreen
        Next FoundCell
    End If

End Sub
该子例程搜索某个字符串并返回填充搜索条件的单元格集合。然后,您可以对该集合中的单元格执行任何操作。忘记添加
FindAll
函数定义:

Function FindAll(SearchRange As Range, _
                FindWhat As Variant, _
               Optional LookIn As XlFindLookIn = xlValues, _
                Optional LookAt As XlLookAt = xlWhole, _
                Optional SearchOrder As XlSearchOrder = xlByRows, _
                Optional MatchCase As Boolean = False, _
                Optional BeginsWith As String = vbNullString, _
                Optional EndsWith As String = vbNullString, _
                Optional BeginEndCompare As VbCompareMethod = vbTextCompare) As Range
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' FindAll
' This searches the range specified by SearchRange and returns a Range object
' that contains all the cells in which FindWhat was found. The search parameters to
' this function have the same meaning and effect as they do with the
' Range.Find method. If the value was not found, the function return Nothing. If
' BeginsWith is not an empty string, only those cells that begin with BeginWith
' are included in the result. If EndsWith is not an empty string, only those cells
' that end with EndsWith are included in the result. Note that if a cell contains
' a single word that matches either BeginsWith or EndsWith, it is included in the
' result.  If BeginsWith or EndsWith is not an empty string, the LookAt parameter
' is automatically changed to xlPart. The tests for BeginsWith and EndsWith may be
' case-sensitive by setting BeginEndCompare to vbBinaryCompare. For case-insensitive
' comparisons, set BeginEndCompare to vbTextCompare. If this parameter is omitted,
' it defaults to vbTextCompare. The comparisons for BeginsWith and EndsWith are
' in an OR relationship. That is, if both BeginsWith and EndsWith are provided,
' a match if found if the text begins with BeginsWith OR the text ends with EndsWith.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim FoundCell As Range
Dim FirstFound As Range
Dim LastCell As Range
Dim ResultRange As Range
Dim XLookAt As XlLookAt
Dim Include As Boolean
Dim CompMode As VbCompareMethod
Dim Area As Range
Dim MaxRow As Long
Dim MaxCol As Long
Dim BeginB As Boolean
Dim EndB As Boolean
CompMode = BeginEndCompare
If BeginsWith <> vbNullString Or EndsWith <> vbNullString Then
    XLookAt = xlPart
Else
    XLookAt = LookAt
End If
' this loop in Areas is to find the last cell
' of all the areas. That is, the cell whose row
' and column are greater than or equal to any cell
' in any Area.

For Each Area In SearchRange.Areas
    With Area
        If .Cells(.Cells.Count).Row > MaxRow Then
            MaxRow = .Cells(.Cells.Count).Row
        End If
        If .Cells(.Cells.Count).Column > MaxCol Then
            MaxCol = .Cells(.Cells.Count).Column
        End If
    End With
Next Area
Set LastCell = SearchRange.Worksheet.Cells(MaxRow, MaxCol)
On Error GoTo 0
Set FoundCell = SearchRange.Find(what:=FindWhat, _
        after:=LastCell, _
        LookIn:=LookIn, _
        LookAt:=XLookAt, _
        SearchOrder:=SearchOrder, _
        MatchCase:=MatchCase)
If Not FoundCell Is Nothing Then
    Set FirstFound = FoundCell
    Do Until False ' Loop forever. We'll "Exit Do" when necessary.
        Include = False
        If BeginsWith = vbNullString And EndsWith = vbNullString Then
            Include = True
        Else
            If BeginsWith <> vbNullString Then
                If StrComp(Left(FoundCell.Text, Len(BeginsWith)), BeginsWith, BeginEndCompare) = 0 Then
                    Include = True
                End If
            End If
            If EndsWith <> vbNullString Then
                If StrComp(Right(FoundCell.Text, Len(EndsWith)), EndsWith, BeginEndCompare) = 0 Then
                    Include = True
                End If
            End If
        End If
        If Include = True Then
            If ResultRange Is Nothing Then
                Set ResultRange = FoundCell
            Else
                Set ResultRange = Application.Union(ResultRange, FoundCell)
            End If
        End If
        Set FoundCell = SearchRange.FindNext(after:=FoundCell)
        If (FoundCell Is Nothing) Then
            Exit Do
        End If
        If (FoundCell.Address = FirstFound.Address) Then
            Exit Do
        End If
    Loop
End If
Set FindAll = ResultRange
End Function
函数FindAll(搜索范围作为范围_
找到什么作为变体_
可选的LookIn为XlFindLookIn=xlValues_
可选的注视方式为XlLookAt=xlWhole_
可选的SearchOrder为XlSearchOrder=xlByRows_
可选MatchCase作为布尔值=False_
可选的BeginsWith As String=vbNullString_
可选EndsWith As String=vbNullString_
可选的BeginEndCompare作为VbCompareMethod=vbTextCompare)作为范围
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
芬德尔
'这将搜索SearchRange指定的范围并返回一个范围对象
'包含在其中找到的所有单元格。将搜索参数设置为
“此功能的含义和作用与
'范围。查找方法。如果未找到该值,函数将不返回任何内容。如果
'BeginsWith不是空字符串,只有以BeginWith开头的单元格才是空字符串
结果中包括了。如果EndsWith不是空字符串,则仅显示这些单元格
'结果中包括以EndsWith结尾的。请注意,如果单元格包含
'匹配BeginsWith或EndsWith的单个单词,包含在
"结果,。如果BeginsWith或EndsWith不是空字符串,则LookAt参数
'自动更改为xlPart。BeginsWith和EndsWith的测试可能是
'通过将BeginedCompare设置为vbBinaryCompare区分大小写。不区分大小写
'比较,将BeginedCompare设置为vbTextCompare。如果省略此参数,
'它默认为vbTextCompare。BeginsWith和EndsWith的比较如下
“在一段关系中。也就是说,如果同时提供了BeginsWith和EndsWith,
'如果文本以BeginsWith开头或以EndsWith结尾,则找到匹配项。
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
作为射程的Dim-FoundCell
作为射程首次发现
将最后一个单元格设置为范围
Dim ResultRange As范围
暗XLookAt作为XlLookAt
Dim Include作为布尔值
将CompMode设置为VbCompareMethod
模糊区域作为范围
Dim MaxRow尽可能长
暗淡的马克斯科尔一样长
Dim BeginB作为布尔值
Dim EndB作为布尔值
CompMode=beginedcompare
如果以vbNullString开头或以vbNullString结尾,则
XLookAt=xlPart
其他的
XLookAt=LookAt
如果结束
'区域中的此循环用于查找最后一个单元格
"在所有领域中,。也就是说,其行
'和列大于或等于任何单元格
“在任何地方。
用于SearchRange中的每个区域。区域
面积
如果.Cells(.Cells.Count).Row>MaxRow,则
MaxRow=.Cells(.Cells.Count).Row
如果结束
如果.Cells(.Cells.Count).Column>MaxCol,则
MaxCol=.Cells(.Cells.Count).Column
如果结束
以
下一个领域
设置LastCell=SearchRange.Worksheet.Cells(MaxRow,MaxCol)
错误转到0
Set FoundCell=SearchRange.Find(what:=FindWhat_
之后:=最后一个单元格_
LookIn:=LookIn_
瞧:=XLookAt_
SearchOrder:=SearchOrder_
匹配案例:=匹配案例)
如果不是FoundCell,那就什么都不是了
Set FirstFound=FoundCell
直到永远“假”循环。必要时我们会“退出”。
Include=False
如果BeginsWith=vbNullString,EndsWith=vbNullString,则
Include=True
其他的
如果以vbNullString开头,则
如果StrComp(左(FoundCell.Text,Len(BeginsWith)),BeginsWith,beginedcompare)=0,则
Include=True
如果结束
如果结束
如果EndsWith vbNullString,则
如果StrComp(Right(FoundCell.Text,Len(EndsWith)),EndsWith,beginedcompare)=0,则
Include=True
如果结束
如果结束
如果结束
如果Include=True,则
如果ResultRange什么都不是,那么
Set ResultRange=FoundCell
其他的
Set ResultRange=Application.Union(ResultRange,FoundCell)
如果结束
如果结束
设置FoundCell=SearchRange.FindNext(后面:=FoundCell)
如果(FoundCell为Nothing),则
退出Do
如果结束
如果(FoundCell.Address=FirstFound.Address),则
退出Do
如果结束
环
如果结束
Set FindAll=ResultRange
端函数

您可以使用带有通配符的
Like
运算符来确定字符串中是否存在给定的子字符串,例如:

If cell.Value Like "*Word1*" Then
'...
ElseIf cell.Value Like "*Word2*" Then
'...
End If
在本例中,
“*Word1*”
中的
*
字符是一个通配符,与零个或多个字符匹配


注意:
Like
运算符是区分大小写的,因此
“Word1”Like“Word1”
为false,可以找到更多信息。

查找或使用
Like
-注意它区分大小写。