Excel使用vbTextCompare循环遍历单元格以指定类别

时间:2013-05-21 08:59:07

标签: excel vba excel-vba foreach text-comparison

我有一个电子表格,其中包含每行的摘要列(列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

它将返回正确的字符串。

1 个答案:

答案 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个单词