VBA – 如何循环

我很新,我陷入了困境。

如果我有列A(A1:A10)中的文本string,让我们说。 我有一个macros,该string中查找关键字,如果它发现我想要一个字被input到列B(B1:B10)。

例如A1-必胜客 – B1比萨,A2汉堡王–B2汉堡。

我已经到了可以find关键字的地步,但是当我尝试做任何可能会在范围内循环的事情时,我总是会得到与B相同的结果。

使用For Each Loop和Split:

Option Explicit Public Sub Example() Dim Sht As Worksheet Dim rng As Range Set Sht = ActiveWorkbook.Sheets("Sheet2") For Each rng In Sht.Range("A1", Range("A11").End(xlUp)) rng.Offset(0, 1).Value = Split(rng, " ")(0) Next Set Sht = Nothing Set rng = Nothing End Sub 

谢谢你的答案。 我以为我张贴我的代码,但我想它没有。 无论如何,我在网上查找了一整天之后find了一种方法。

 Sub one() Dim food As String, type As String Dim rng As Range Dim cel As Range Set rng = Range("A:A") For Each cel In rng food = cel.Value If InStr(UCase(food), UCase("pizza")) <> 0 Then type = "Fast food" Elseif InStr(UCase(food), UCase("burger")) <> 0 Then type = "Fast food" Else type = "Not Fast food" End If cel.offset (0, 1).Value = type Next cel End Sub 

这应该做你想要的:

 Sub Find_and_Copy(): Dim keywords() As Variant keywords = Array("Pizza", "Burger", "Chicken") Dim endRow As Integer Dim SearchRng As Range With Sheets("Sheet1") endRow = .Cells(Rows.Count, "A").End(xlUp).Row Set SearchRng = .Range("A1:A" & endRow).Cells End With Dim r As Range Dim firstAddress As String Dim i As Integer For i = 0 To UBound(keywords): With SearchRng Set r = .Find(keywords(i), LookIn:=xlValues) If Not r Is Nothing Then firstAddress = r.Address Do Cells(r.Row, "B").Value = keywords(i) Set r = .FindNext(r) Loop While Not r Is Nothing And r.Address <> firstAddress End If End With Next End Sub 

它将查找与“A”列的单元格匹配的“关键字”数组中的每个条目的所有匹配项 – 当然,也可以将列“B”设置为该关键字。

请注意,如果您有“ala Burger Chicken”这样的条目,那么会在该行的B列中放入“Chicken”(我将其添加到“关键字”中以保持事物的精神),因为这是最后一件事search – 因此覆盖在该单元中的前一个“汉堡”条目。