2013-05-21 33 views
2

我有一個電子表格,其中包含每行的彙總列(列K)。我需要匹配概要列中的某些單詞,以便在新列(第V列)中分配類別名稱。Excel使用vbTextCompare遍歷單元格以分配類別

我試着用一個正常的excel來做這件事如果陳述,但我有sinc發現有一個限制。所以現在我試圖使用下面的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

它將返回正確的字符串。

回答

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個字

+0

這工作輝煌謝謝:) – jampez77

+0

+1好asnwer daddio –

相關問題