Wednesday, April 6, 2011

Macro Plug in

Currently this macro is set up so that if Column G has “Last Term” and “Okay” or “Okay” and “Stay” next to each other 07a will be entered into the same row in Column I. I would like to modify this code so that If Column G contains “Last Term” and Column K contains “Okay” and “End” or “Okay” and “Stay” in any combination or in any order, possibly with other words in between, before, or behind them as long as these two different combinations are present then 07a will be entered into Column I in the same row.

Sub Plugin() Dim nRow As Long Dim iRow As Long

nRow = ActiveSheet.Cells(Rows.Count, "G").End(xlUp).Row

For iRow = 1 To nRow
    With Cells(iRow, "G")
        If .Text Like "Okay*" Or .Text Like "End*" Then
            Cells(iRow, "I") = "07a"
        If .Text Like "Okay*" Or .Text Like "Stay*" Then
            Cells(iRow, "I") = "07a"
        End If
    End With
Next iRow

End Sub

From stackoverflow
  • Try the following code:

    Sub Plugin()
    Dim nRow As Long
    Dim iRow As Long
    Dim KUpperText As String
    
    nRow = ActiveSheet.Cells(Rows.Count, "G").End(xlUp).Row
    
    For iRow = 1 To nRow
        KUpperText = UCase(Cells(iRow, "K").Text)
        If UCase(Cells(iRow, "G").Text) Like UCase("Last Term*") Then
            If ((KUpperText Like "*END*" And KUpperText Like "*OKAY*") _
             Or (KUpperText Like "*STAY*" And KUpperText Like "*OKAY*")) Then
                Cells(iRow, "I") = "07a"
            End If
        End If
    Next iRow
    End Sub
    

    For each loop, I read the Text string in column K. It is formatted in upper case to be sure that both "End" and "END" are handled for example.

    barrowc : When using the With statement, there's no problem with testing or setting the attributes of the referenced object. That's pretty much the purpose of the With statement
    Damien : @barrowc You are absolutely right. I've tested adding the "With" and it also works. I've edited my answer to remove the incorrect statement.

0 comments:

Post a Comment