2013-03-28 137 views
1

我想修改我找到的代碼。它是一個VBA函數,用於搜索單元格值的所有實例,然後將每個實例的單元格值返回到一個單元格中。我試圖只返回尚未找到的值,因此最終得到一個不包含重複項的單元格。Excel宏VBA不Instr

原始代碼:

Function Lookup_concat(Search_string As String, _ 
Search_in_col As Range, Return_val_col As Range) 
Dim i As Long 
Dim result As String 
For i = 1 To Search_in_col.Count 
If Search_in_col.Cells(i, 1) = Search_string Then 
result = result & " " & Return_val_col.Cells(i, 1).Value 
End If 
Next 
Lookup_concat = Trim(result) 
End Function 

我已經修改了代碼,這一點,我已經縮進的編輯,而不是將其保持在同一直線上,使其更易於閱讀

Function Lookup_concat(Search_string As String, _ 
Search_in_col As Range, Return_val_col As Range) 
Dim i As Long 
Dim result As String 
For i = 1 To Search_in_col.Count 
If Search_in_col.Cells(i, 1) = Search_string 
     And Not (InStr(1, result, Return_val_col.Cells(i, 1).Value)) Then 
result = result & " " & Return_val_col.Cells(i, 1).Value 
End If 
Next 
Lookup_concat = Trim(result) 
End Function 

這版本是最接近PHP !strstr函數(我明白),也許嘗試將PHP技術應用於VBA是我出錯的地方。我的想法是,結果字符串實際上填充後我的Instr命令,這就是爲什麼它不起作用。

回答

2

我相信你正在嘗試使用兩個If s。您只想根據字符串在範圍內進行添加,並且僅在尚未添加字符串的情況下進行添加。

試試這個:

Function Lookup_concat(Search_string As String, _ 
Search_in_col As Range, Return_val_col As Range) 
    Dim i As Long 
    Dim result As String 

    For i = 1 To Search_in_col.Count 

     If (Instr(1, Search_in_col.Cells(i, 1), Search_string) > 0) 
      And (InStr(1, result, Return_val_col.Cells(i, 1).Value) = 0) Then 

     result = result & " " & Return_val_col.Cells(i, 1).Value 

     End If 

    Next 

    Lookup_concat = Trim(result) 

End Function 
+0

完美,謝謝!對不起,由於反應遲緩,自上週以來我一直沒有上班 – JoeP

2

這是你在找什麼?

Function Lookup_concat(Search_string As String, Search_in_col As Range, Return_val_col As Range) 
    Dim i As Long 
    Dim result As String 
    For i = 1 To Search_in_col.Count 
     If InStr(1, Search_in_col.Cells(i, 1).Value, Search_string, vbTextCompare) > 0 Then 
      result = result & " " & Return_val_col.Cells(i, 1).Value 
     End If 
    Next 
    Lookup_concat = Trim(result) 
End Function 
1

不完全相信你與Search_in_colReturn_val_col做什麼,但你一定要使用If Instr() > 0測試。

如果結果> 1,那麼你可能不需要做任何事情。如果這個結果爲0,那麼你將需要做你的連接。這是我不確定爲什麼通過search_in_col.cells(i,1).Value作爲搜索參數,但然後連接Return_val_col.Cells(i,1).Value,所以你實際上並沒有連接你使用的值作爲搜索參數的部分...

'if the cell's value exists in the search_string 
If InStr(1, Search_in_col.Cells(i, 1).Value, search_string, vbBinaryCompare) > 0 Then 
    'probably you want to do nothing here, since it's already existing 
Else: 
    'the cell's value does not exist in the search_string, so concatenate it 
    result = result & " " & "whatever value you want to append to the result" 
End If 
+0

很好的解釋,謝謝。我已經接受了previsou的答案,但這當然非常有幫助 – JoeP