如何在列表中列出variables的所有位置?

我有一大串文本string。 我知道一些string在这个列表中不止一次出现。 string出现的频率在下一列。

现在,让我们说,文本string“你好”出现17次。 我怎样才能得到这个文本的所有位置?

任何帮助表示赞赏。

假设你所有的string都在一列中,你可以在它们的位置(行号)上添加第二列,并在显示计数的string上做一个数据透视表。

为了得到你感兴趣的string的位置,你可以使用数据透视表的下钻function(双击string旁边的计数),这将创build一个新的工作表和所有的细节logging – 位置将被显示

希望有所帮助

好locking

交换意见后编辑:

我会去一个解决scheme,只扫描一次你的数据,而不是recursion的,将值复制到第二个表:

for each string in sourcetable if found in targettable increase targettable.counter by 1 (remark: in column_2) else put sourcetable.string at end of targettable put "1" in targettable.counter (remark: occurence = 1 in column_2) endif put sourcetable.index into targettable.column(counter+2) next 

到目前为止的元代码….你需要更多的帮助,实际上在VBA编码?

编辑2

好….做了一个快速和肮脏的一个….

 Sub CountString() Dim S As Range, T As Range, Idx As Long, Jdx As Long Set S = Worksheets("Sheet1").[A2] ' first row is header Set T = Worksheets("Sheet2").[A2] ' first row is header Idx = 1 Do While S(Idx, 1) <> "" Jdx = FindInRange(T, S(Idx, 1)) If T(Jdx, 1) = "" Then T(Jdx, 1) = S(Idx, 1) T(Jdx, 2) = 1 T(Jdx, 3) = Idx Else T(Jdx, 2) = T(Jdx, 2) + 1 T(Jdx, T(Jdx, 2) + 2) = Idx End If Idx = Idx + 1 Loop End Sub Function FindInRange(R As Range, A As String) As Long Dim Idx As Long Idx = 1 Do While R(Idx, 1) <> "" If R(Idx, 1) = A Then Exit Do End If Idx = Idx + 1 Loop FindInRange = Idx End Function 

用“Lorem ipsum”中的500个单词进行testing – 在1秒以内,sheet_2中的输出看起来像

 String Count Position ... Lorem 1 1 ipsum 6 2 45 65 232 323 462 dolor 5 3 42 214 321 335 sit 6 4 79 148 249 295 415 amet 6 5 80 149 250 296 416 consectetur 8 6 117 288 298 396 457 473 486 adipiscing 3 7 180 402 

希望有所帮助

彼得,

看看这个堆栈溢出的post 。

我也试图调整他们的示例代码来匹配你的情况,我很抱歉,虽然这可能不会编译,我不能在此刻testing,我的VBA有点生疏,但你明白了。

 Function CheckValues1(byval columnToCheck as Integer, byval stringToFind as String) as Integer() dim rwIndex As Integer dim index as Integer dim occurrences() As Integer index = 0 For rwIndex = 0 to Cells(Rows.Count, columnToCheck).End(xlUp).Row ReDim Preserve occurrences(0 to index) If Cells(rwIndex, columnToCheck).Value = stringToFind Then occurrences(index) = rwIndex index = index + 1 End If Next rwIndex dim output as String output = output & (Len(occurrences)-1) & " occurrences found." & vbcrlf & vbcrlf For index = 0 to LBound(occurrences) output = output & "Line: " & index & vbcrlf Next index MsgBox output End Sub 

这个函数应该返回一个你可以处理的所有事件的数组。 你只需要通过你正在寻找的string和列号进行search。

我希望这有帮助!

托尼