我该如何检查特定列中的所有行是否包含使用VBA的Excel中的特定string?

我有不同的表中的2列数据。 我们可以称它们为A,BB比A有更多的数据行,数据也不相同。 具体来说,在每个数据字段中有一些额外的文本追加在B的结尾或开始在B我试图找出所有可能的行在B中包含A中的每一行

有多种方法。 这取决于你想要做什么。

循环行。

Dim ws As Excel.Worksheet Dim lRow As Long Set ws = ActiveWorkbook.Sheets("Sheet1") ws.Activate lRow = 1 'Loop through and record what is in the first column Do While lRow <= ws.UsedRange.Rows.count If ws.Range("A" & lRow).Value = "SomeValue" Then 'Do something here End if lRow = lRow + 1 ws.Range("A" & lRow).Activate Loop 

或者你可以在一个范围内使用find和findnext。 这将在范围a1:a500中查找值“2”。

 With Worksheets(1).Range("a1:a500") Set c = .Find(2, lookin:=xlValues) If Not c Is Nothing Then firstAddress = c.Address Do c.Value = 5 Set c = .FindNext(c) Loop While Not c Is Nothing And c.Address <> firstAddress End If End With 

你的问题可以从进一步的澄清中受益。 EG一些示例数据。

我想你在说什么:

A包含例如

 "test1" "test2" "test3" 

B包含例如

 "Test1-BData" "Bdata2-Test3" "Bdata3-Test1" 

在这种情况下。 你需要在A中定义string的长度

 dim lngColumnAStringLength as long lngColumnAStringLength = 5 dim strTest as string for I = '/start column B to '/ End column B strTest = left(columnBcell, X) strTest = right(columnBcell, X) '/ Returns the first (or last) X characters of the string bMatchFound = false for j = '/ startcolumn A to end column A if strTest = (columnAcell.text) then bMAtchFound = true next j if BMatchFound = true then '/ Copy to a 3rd list, hide row, whatever next i 

或者,如果您的数据总是附加一个分隔符,例如“ – ”或“。” 或类似的东西。 您可以使用

 split(columnBtext, "-") 

如果B =“abc-def-ghij”返回一个包含(“abc”,“def”,“ghij”)的数组