2016-04-19 160 views
2

我比這個更新,而且我無法整理For ... Next循環。在兩個範圍內的VBA搜索

我想跟蹤兩列中的兩個文本變量,這樣當在一行中找到兩個變量時,文本就會添加到不同列中的那一行。

這是我到目前爲止有:

Sub AB() 
Dim Rng1 As Range 
Dim Rng2 As Range 
Set Rng1 = Range("B1:B100") 
Set Rng2 = Range("A1:A100") 
For Each cel In Rng1 
    If InStr(1, cel.Value, "A") > 0 Then 
    For Each cel In Rng2 
     If InStr(1, cel.Value, "B") > 0 Then 
      cel.Offset(0, 5).Value = "AB" 
     End If 
    Next 
    End If 
Next cel 

End Sub 
+0

移動內環第一個'if'外,如果結合的發言等'如果InStr函數(1,cel.Value, 「A」)> 0和如果InStr函數(1,cel.Value,「B 「)> 0然後'編輯:你需要聲明一個'cel2'。 – findwindow

回答

2

你甚至可能能夠只是做到這一點?

Sub AB() 

With ActiveSheet 

For I = 1 To 100 

    If InStr(1, .Cells(I, 2), "A") > 0 And InStr(1, .Cells(I, 1), "B") > 0 Then 
     .Cells(I, 6).Value = "AB" 'i think offset 5 is column F? 
    End If 

Next 

End With 

End Sub 
+0

謝謝!這工作。 – pvxl1989

+0

不客氣。 – findwindow

0

您正在使用`cel'來遍歷每個循環 - 內部循環會感到困惑。

沿着@findwindow答案的靜脈(出現在我打字時)。循環一次,當找到匹配時,檢查它旁邊的單元格。

Sub AB() 

    Dim Rng1 As Range 
    Dim Rng2 As Range 
    Dim cel1 As Range 

    'Be specific about which sheet your ranges are on. 
    With ThisWorkbook.Worksheets("Sheet1") 
     Set Rng1 = .Range("B1:B100") 
     Set Rng2 = .Range("A1:A100") 
    End With 

    For Each cel1 In Rng1 
     'Check each value in column B. 
     If InStr(1, cel1.Value, "A") > 0 Then 
      'If a match is found, check the value next to it. 
      If InStr(1, cel1.Offset(, -1), "B") > 0 Then 
       cel1.Offset(, 4).Value = "AB" 
      End If 
     End If 
    Next cel1 

End Sub 
+0

謝謝。兩者都有效。 – pvxl1989

1

欣賞你現在有一個答案,但這裏有一個使用Find的不同方法。總是很好地知道幾種做某事的方法。

Sub AB() 

Dim rng As Range 
Dim itemaddress As String 

With Columns(1) 

Set rng = .Find("A", searchorder:=xlByRows, lookat:=xlWhole) 

    If Not rng Is Nothing Then 

     itemaddress = rng.Address 

     Do 
      If rng.Offset(0, 1) = "B" Then 
       rng.Offset(0, 2).Value = "AB" 
      End If 

     Set rng = .FindNext(rng) 
     Loop While Not rng Is Nothing And itemaddress <> rng.Address 

    End If 

End With 

End Sub