vba Excel宏根据行中其他两列的值写入值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28613586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 06:17:29  来源:igfitidea点击:

Excel Macro to write value based on value of two other columns in row

excelvbaexcel-vba

提问by Lonememe

I have a pickle that I was hoping to get some help with. I cobbled together a macro the other day following this logic:

我有一个泡菜,我希望能得到一些帮助。前几天我按照这个逻辑拼凑了一个宏:

If a cell in column B has a particular text, "brand1", and that row has the value "y" in column U, then populate column W of that row with a text string, "sample1".

如果 B 列中的单元格具有特定文本“brand1”,并且该行在 U 列中具有值“y”,则用文本字符串“sample1”填充该行的 W 列。

I had it working the other day, but for some reason it's not working today. Any ideas or thoughts? Totally open to the idea of scrapping this macro anyway and using a different one.

前几天我让它工作,但由于某种原因它今天不起作用。有什么想法或想法吗?完全接受废弃这个宏并使用不同的宏的想法。

Sub PromoID()

Application.ScreenUpdating = False
Dim lastRow As Long
Dim cell As Range
lastRow = Range("B" & Rows.Count).End(xlUp).Row

For Each cell In Range("B2:B" & lastRow)
    If InStr(1, cell.Value, "Brand1") <> 0 Then
    InStr(1, cell.Offset(, 21).Value, "y") <> 0 Then
            cell.Offset(, 23).Value = "sample1"
        End If
    End If
Next

Application.ScreenUpdating = True
End Sub

采纳答案by Amen Jlili

You were not that far from the answer. Keep your eyes peeled for minor errors.

你离答案不远了。留意小错误。

Sub PromoID()

Application.ScreenUpdating = False
Dim lastRow As Long
Dim cell As Range
lastRow = Range("B" & Rows.Count).End(xlUp).Row + 1

For Each cell In Range("B2:B" & lastRow)
    If InStr(1, cell.Value, "Brand1") <> 0 Then
    If InStr(1, cell.Offset(0, 19).Value, "y") <> 0 Then
            cell.Offset(0, 21).Value = "sample1"
        End If
    End If
Next

Application.ScreenUpdating = True
End Sub

Output:

输出:

enter image description here

在此处输入图片说明

回答by Distelzombie

Try to make everything uppercase. With Ucase()

尝试使所有内容大写。使用 Ucase()

If ucase(InStr(1, cell.Value, "Brand1") ) <> 0 Then ucase(InStr(1, cell.Offset(, 21).Value, "y") ) <> 0 Then cell.Offset(, 23).Value = "sample1"