我编写了下面显示的条件,它查找A行中的值“当前状态:”并将B值从该行复制到其他工作表,如果找不到"0“放置在单元格中,则可以正常工作。有时值“当前状态:”可能位于与A18不同的单元格中,它可能出现在从A16到A20的范围内,我如何修改该代码以在范围内找到它并复制相应的值?
If ws.Range("A18") = "Current Status:" Then
.Range("V" & NewRow) = ws.Range("B18")
Else
.Range("V" & NewRow) = "0"
End If
发布于 2017-10-11 13:23:32
只要把你的代码放在一个For
循环中..。或者像斯科蒂建议的那样使用VLookup
。基本上是一样的。For
循环更灵活,但优化程度较低(VLookup
更快)。它们都是按照μs/cell的分数顺序运行的。
For Each c In Range("A16:A20")
If c.Value2 = "Current Status:" Then
.Range("V" & NewRow) = c.Offset(0, 1)
Exit For
Else
.Range("V" & NewRow) = "0"
End If
Next
如果使用For
循环,这会比上面的代码多一点,但是结构更好.
'Define a value holder variable where it's scope makes sense
Dim NewValue As String
'... other code here ...
'Default: NewValue = ""
NewValue = ""
For Each c In Range("A16:A20")
If c.Value2 = "Current Status:" Then
NewValue = c.Offset(0, 1)
'Exit For is optional in this case. It matters if
'there are multiple matches... do you want first or last result?
Exit For
End If
Next
'Assign NewValue to cell
.Range("V" & NewRow) = NewValue
发布于 2017-10-11 13:16:49
使用Vlookup:
.Range("V" & NewRow) = "0"
On Error Resume Next
.Range("V" & NewRow) = Application.WorksheetFunction.VLookup("Current Status:", ws.Range("A:B"), 2, False)
On Error GoTo 0
这将把0放在单元格中,然后尝试用从vlookup返回的值替换它。如果在"Current Status:"
的A列中找不到ws
,那么它将抛出一个错误并被忽略,将0
留在单元格中。
如果找到该值,它将返回B列中的值,并将其替换为0
https://stackoverflow.com/questions/46689164
复制相似问题