VBA在两个范围内search

我比这更新颖,而且在排列For … Next循环时遇到了麻烦。

我想跟踪到两列中的两个文本variables,以便在一行中find两个variables时,将文本添加到不同列中的该行。

这是我迄今为止:

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 

你甚至可以做到这一点?

 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 

欣赏你现在有一个答案,但这里是使用查找不同的方法。 总是很好地知道几种方法来做一些事情。

 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 

你使用`cel'来遍历每一个循环 – 内部循环会变得困惑。

沿@findwindow答案的静脉(出现在我打字时)。 循环一次,当find一个匹配时,检查旁边的单元格。

 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