Home » excel » excel – Changing a value of a cell based on another cell

excel – Changing a value of a cell based on another cell

Posted by: admin May 14, 2020 Leave a comment

Questions:

What I want to do is if column O contains “weekend” then change the value of column M cells to “3”.

Sub weekly_weekend()
  lastrow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
  Application.ScreenUpdating = False

  For x = 2 To lastrow
   If InStr(1, Sheet1.Range("O" & x).Value, UCase("weekend"), 1) > 0 Then 
     Sheet1.Range("M" & x).Value = "3"
  Next x

  Application.ScreenUpdating = True
End Sub
How to&Answers:

The problem with your code is that you’re getting the last row of the column A, and this will prevent the For to be executed. To fix your code, you can proceed in multiple ways.

Using Range

  • One is to use the Range property, so you can explicitly write your column name, like this:

    Sub weekly_weekend()
        lastrow = Sheet1.Range("O" & Sheet1.Rows.Count).End(xlUp).Row
        Application.ScreenUpdating = False
    
        For x = 2 To lastrow
            If InStr(1, Sheet1.Range("O" & x).Value, UCase("weekend"), 1) > 0 Then Sheet1.Range("M" & x).Value = "3"
        Next x
    
        Application.ScreenUpdating = True
    End Sub
    

Picking up the right column

  • Or you can simply pick the right number of the column you want (in this case column O is 15), like this:

    Sub weekly_weekend()
        lastrow = Sheet1.Cells(Sheet1.Rows.Count, 15).End(xlUp).Row
        Application.ScreenUpdating = False
    
        For x = 2 To lastrow
            If InStr(1, Sheet1.Range("O" & x).Value, UCase("weekend"), 1) > 0 Then Sheet1.Range("M" & x).Value = "3"
        Next x
    
        Application.ScreenUpdating = True
    End Sub
    

Note: Please note that if you add or remove columns, with the second method you’ll need to remember to change the column index in your code accordingly.

Hope this helps.