我一般都不熟悉编码,因此需要编写一个宏。下面的代码在一个字段中搜索文本,如果是,它将从该列中获取一个数量并将其复制到另一个单元格中。然后对整个行重复一次,这行得通,但是单元格中的文本必须准确。
Sub Test()
Dim variable As String
variable = "insert value or cell here"
With Sheets("Test")
LR = .Cells(Rows.Count, "N").End(xlUp).Row
For i = LR To 2 Step -1
If .Cells(i, "N").Value = "Blue" Or .Cells(i, "N").Value = "Red" Or .Cells(i, "N").Value = "Green" Then
.Cells(i, "AV").Value = .Cells(i, "P").Value
End If
Next i
End With
End Sub
通过一些在线查找,我整理了以下代码,如果值出现在该单元格的任何位置,则返回正数,但我无法使其正常工作。任何帮助表示赞赏。
Sub Test()
Dim variable As String
variable = "insert value or cell here"
With Sheets("Test")
LR = .Cells(Rows.Count, "M").End(xlUp).Row
For i = LR To 2 Step -1
If InStr(.Cells(i, "M"), Value = "Red" or Value = "Green" or Value = "Blue") Then
.Cells(i, "AV").Value = .Cells(i, "P").Value
Else: .Cells(i, "AV").Value = "0"
End If
Next i
End With
End Sub
答案 0 :(得分:0)
您的instr()
的简单拆分:
If InStr(.Cells(i, "M").Value,"Red") > 0 Or InStr(.Cells(i, "M").Value,"Green") > 0 or InStr(.Cells(i, "M").Value,"Blue") > 0 Then
根据我的评论,请记住:
InStr(,)
接受一个参数,确定要寻找的位置,第二个参数则确定要寻找的位置。它输出很长。
如您所写,InStr()
的隐式响应使用不当会引起混乱,因此您需要在条件中添加“> 0。
这将是一个真实的条件:
Dim str as string
str = "cat"
If InStr(str, "a") Then
在这种情况下,InStr
返回一个值的事实被认为是“ true”,因为隐式响应...但是下一个将是false:
Dim str as string
str = "cat"
If InStr(str, "a") And InStr(str, "c") Then
移至第二个条件时,将删除“是的,这有结果”,这意味着并非两种情况都成立。为了使以上内容正确无误,我们将添加关于InStr()
返回Long
(非布尔值)的条件:
Dim str as string
str = "cat"
If InStr(str, "a") > 0 And InStr(str, "c") > 0 Then
第一个InStr()
返回2,因此为true,第二个InStr()
返回1,因此为true ...