[英]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". 我想做的是,如果O列包含“ weekend”,则将M列的值更改为“ 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. 代码的问题在于,您将获得
column A
的最后一行,这将阻止执行For
。 To fix your code, you can proceed in multiple ways. 要修复您的代码,您可以采用多种方式进行。
One is to use the Range
property, so you can explicitly write your column name, like this: 一种是使用
Range
属性,因此您可以显式编写列名,如下所示:
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
Or you can simply pick the right number of the column you want (in this case column O
is 15
), like this: 或者,您可以简单地选择所需列的正确编号(在这种情况下,
column O
为15
),如下所示:
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. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.