我有一个电子表格,其中包含每行的摘要列(列K)。我需要匹配摘要列中的某些单词,以便在新列(第V列)中指定类别名称。
我尝试使用普通的excel If语句执行此操作,但我发现有一个限制。所以现在我正在尝试使用以下VBA代码。
Public Function getCategory()
V_End_Of_Table = ActiveSheet.UsedRange.Rows.Count 'count the number of rows used'
Dim cell As Range
For Each cell In Range("K2:K" & V_End_Of_Table) 'loop through each row until end of table'
If InStr(1, cell.Value, "Nationalities", vbTextCompare) > 0 Then
Range("V" & V_End_Of_Table).Value = "Nationalities"
Else
Range("V" & V_End_Of_Table).Value = "No Match Found"
End If
Next 'move onto next cell'
End Function
所以我试图遍历每一行,匹配文本并分配值。因为它刚刚获得#VALUE!回。 如果我改变
范围(“V”& V_End_Of_Table).Value
到
MsgBox
它将返回正确的字符串。
答案 0 :(得分:4)
For Each cell In Range("K2:K" & V_End_Of_Table)
If InStr(1, cell.Value, "Nationalities", vbTextCompare) > 0 Then
Range("V" & cell.Row).Value = "Nationalities"
Else
Range("V" & cell.Row).Value = "No Match Found"
End If
Next
而不是InStr
您可以使用StrComp
函数来比较2个单词