简体   繁体   中英

VBA: Change cell value based on approximate values of other cells

I'm struggling on a piece of VBA that I've written whose purpose would be to change the value of a cell in column B if column G contains certain bits of text. Here's what I've written so far:

Sub Test()
    Dim LastRow As Long
    Dim i As Long
    Sheets("Current Week").Select
    LastRow = Range("G" & Rows.Count).End(xlUp).Row
    For i = 2 To LastRow
        If Range("G" & i).Value Like "*Eagle*" Then
            Range("B" & i).Value = "Bird"
        End If
    Next i
End Sub

Though the above works, I'm struggling is that I'd like to add more "Values like" than just "Eagle". I've tried the following without much success:

Sub Test()
    Dim LastRow As Long
    Dim i As Long
    Sheets("Current Week").Select
    LastRow = Range("G" & Rows.Count).End(xlUp).Row
    For i = 2 To LastRow
        If Range("G" & i).Value Like "*Eagle*" 
        Or ("G" & i).Value Like "*Pelican*"
        Then
        Range("B" & i).Value = "Bird"
        End If
    Next i
End Sub

How do I add more "Values like"?

Thanks!

I think your confusion stems from VB(A)'s requirement of using a line continuation character ( _ ) if you want to break a line up for readability purposes.

' ...

If _
    Range("G" & i).Value Like "*Eagle*" Or _
    Range("G" & i).Value Like "*Pelican*" Or _
    Range("G" & i).Value Like "*Chicken*" Or _
    Range("G" & i).Value Like "*Sparrow*" _
Then
    Range("G" & i).Value = "Bird"
End If

' ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM