我已经编写了一些代码来比较同一工作表中的两个字符串。代码应检查列b中的字符串是否出现在列a中的任何位置。如果字符串出现在列a中,那么值为“是”'应该退还。如果字符串不存在那么“没有”#39;应该退还。字符串的一个例子是' SR03SN56' SR和SN将始终存在,只有数值会改变。我写的代码总是返回'是'或者'否'无论字符串是否存在于列a中。我无法理解为什么虽然我有一种感觉,但我使用了strcmp功能。非常感谢任何帮助。
Public Sub NameLater()
Dim colA As String, colB As String
Dim LastRowA As Integer, LastRowB As Integer, i As Integer, j As Integer
Dim Comparison As Integer
Dim Result As String
With ActiveSheet
LastRowA = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
With ActiveSheet
LastRowB = .Cells(.Rows.Count, "B").End(xlUp).Row
End With
For i = 1 To LastRowA
For j = 2 To LastRowB
colA = Range("A" & i).Value
colB = Range("B" & j).Value
Comparison = StrComp(colA, colB, 1)
If Comparison = 1 Then Result = "Yes"
If Comparison = 0 Then Result = "No"
If Comparison = -1 Then Result = "No"
Sheet2.Range("H" & j).Value = Result
Next j
Next i
End Sub
答案 0 :(得分:1)
我建议您使用vlookup而不是VBA:
=IF(IFERROR(VLOOKUP(B1,A:A,1,false),0)=0,"No","Yes")
对于列b的每个单元格,您可以找到列a中是否存在。更容易。