Excel:查找范围内的所有文本string实例并返回每个实例

我需要查找可能出现在一列中的特定标识符的所有实例,并将它们连接成一个string。

标识符将以"ECP"开头,并用短划线或空格分隔,分隔符后面有几个字符。 例如"ECP 05-00012A1, "ECP-123456."

我正在使用下面的公式,但没有考虑多个“ECP数字”。

=INDEX('Raw WAM Data'!$A$1:$A$10000,MATCH(VLOOKUP("*"&"ECP"&"*",'Raw WAM Data'!$A$1:$A$10000,1,FALSE),'Raw WAM Data'!$A$1:$A$10000,0))

然后我使用以下方法parsing相邻单元格中的数据: =LEFT($C$62,FIND(" ", $C$62, FIND(" ", $C$62)+1))然后将该string加载到UserForm文本框。

然后,我需要连接所有返回的值到一个由逗号分隔的string,以便它可以加载到UserForm文本框。

我认为VBA将是理想的,但我愿意接受任何build议。

如果我已经正确理解了你想要达到的目标,那么你可以使用这样的东西:

 Sub TEST() Dim dic As Object: Set dic = CreateObject("Scripting.Dictionary") Dim cl As Range, x& With Sheets("Sheet1") 'replace sheet1 by name of your sheet x = .Cells(Rows.Count, "A").End(xlUp).Row For Each cl In .Range(.[A1], .Cells(x, "A")) If UCase(cl.Value2) Like "ECP*" And Not dic.exists(cl.Value2) Then dic.Add cl.Value2, Nothing End If Next cl End With Debug.Print Join(dic.keys, Chr(10)) End Sub 

testing

在这里输入图像说明


更新

把E列的结果与它所在的单元格相比较,最好的办法是什么? 另外,如果我想search多个列,我应该如何调整代码?

你可以用这种方式:

 Sub TEST2() Dim cl As Range, x& With Sheets("Sheet1") 'replace sheet1 by name of your sheet x = .[A:C].Find("*", , , , xlByRows, xlPrevious).Row 'get the last used row in range For Each cl In .Range(.[A1], .Cells(x, "C")) If UCase(cl.Value2) Like "*ECP*" Then If .Cells(cl.Row, "E").Value2 = "" Then .Cells(cl.Row, "E").Value2 = cl.Value2 Else .Cells(cl.Row, "E").Value2 = .Cells(cl.Row, "E").Value2 & "; " & cl.Value2 End If End If Next cl End With End Sub 

产量

在这里输入图像说明

如果您的值在工作表的A列中,则此例程将收集您的ECP编号并将其加载到数组中。 然后你可以将数组加载到你的TextBox中。

 Sub GatherECPs() Dim ECParr 'Loop down each row starting at row 2 (assuming you have headers) For x = 2 To SourceSheet.Range("A2").End(xlDown).Row 'Check if the start of the string is ECP If Left(SourceSheet.Cells(x, 1).Value, 3) = "ECP" Then 'Add a row to the array If IsEmpty(ECParr) Then ReDim ECParr(0) Else ReDim Preserve ECParr(UBound(ECParr) + 1) End If 'Add the value to the array ECParr(UBound(ECParr)) = Right(SourceSheet.Cells(x, 1).Value, Len(SourceSheet.Cells(x, 1).Value) - 4) End If Next End Sub 

将SourceSheetreplace为您的值存在的工作表。

要在一个单元中同时适用于多个“ECP”的快速方式使用此function:

 Public Function getStr(rng As Range, ident As String) As String Dim i As Long, x As Variant, y As Variant For Each x In Intersect(rng, rng.Parent.UsedRange).Value y = Split(x, ident) If UBound(y) > 0 Then For i = 1 To UBound(y) getStr = getStr & ", " & ident & Split(y(i), ",")(0) Next End If Next getStr = Mid(getStr, 3) End Function 

它将返回一个逗号分隔的string。 只需使用它: getStr(Range("A:A"), "ECP")

如果您还有任何问题,请询问;)