使用VBA,如何在定义的范围内搜索多个字符串?

时间:2016-02-05 12:31:12

标签: excel vba

如果我在A列中有一长串文本,并且在C列中有一个简短的单词列表,那么最好的方法是在A中搜索C中的任何单词中的每个单元格,并复制和将匹配的那些粘贴到B列中?

我到目前为止编写的代码如下

   Sub ListKeywordQualifier()

Dim Rng As Range
Dim Keyword As Range
Dim Chunk As Range
Dim x As Long

x = 1

While x <= 5000
Set Rng = Range("A" & x)
Set Chunk = Range("C1", "C100")

Application.ScreenUpdating = True
Range("D1").Value = x
If Application.WorksheetFunction.CountIf(Chunk, Rng) = 0 Then
x = x + 1

ElseIf Application.WorksheetFunction.CountIf(Chunk, Rng) = 1 Then
Rng.Copy
Rng.Offset(0, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,         SkipBlanks _
    :=False, Transpose:=False
x = x + 1

End If

Wend

End Sub

然而,这将是onl; y给我两者之间的完全匹配。是否可以这样做,但是在C列中出现文本,而只构成A列的一部分,触发复制/粘贴行?

谢谢

2 个答案:

答案 0 :(得分:2)

你的countif不起作用,因为它是一个工作表函数,实现countif ....你需要写它 WorksheetFunction.CountIf。仍然你的代码看起来不错,试一试!

 Sub ListKeywordQualifier()

 Dim Rng(50) As String
 Dim Chunk(50) As String
 Dim i As Long
 i = 1

 '' Take a value From 3rd Column this works for 10 cells , 
 For i = 1 To 10
 Chunk(i) = Cells(i, 3)

  ''Search it in 1st Column in 10 cells
 For j = 1 To 10
   Rng(j) = Cells(j, 1)

 ''If it matches 

   If Chunk(i) = Rng(j) Then

''Then copy that value to Second Column

  Cells(i, 2).Value = Rng(j)

End If

Next j

Next i

End Sub

这只是为了给你一个想法,你还需要做出改变谢谢

答案 1 :(得分:1)

考虑:

200

在:

enter image description here

之后:

enter image description here