VBA在两个范围内搜索

时间:2016-04-19 15:40:21

标签: excel vba excel-vba

我不仅仅是新手,而且我在整理For ... Next循环时遇到了麻烦。

我想跟踪两列中的两个文本变量,这样当一行中找到两个变量时,文本就会被添加到不同列中的那一行。

这是我到目前为止所做的:

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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