1

我正在尝试修改我找到的代码。它是一个 VBA 函数,用于搜索单元格值的所有实例,然后将每个实例的单元格值返回到一个单元格中。我试图只返回尚未找到的值,因此最终得到一个不包含重复项的单元格。

原始代码:

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命令之后填充的,这就是它不起作用的原因。

4

3 回答 3

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
于 2013-03-28T17:19:57.070 回答
2

我相信您正在尝试使用两个Ifs。您只想添加基于范围内的字符串,并且仅在尚未添加字符串的情况下添加。

试试这个:

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
于 2013-03-28T18:20:43.483 回答
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
于 2013-03-28T18:05:44.063 回答