简体   繁体   中英

Changing a value of a cell based on another cell

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

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.

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