查找另一个范围内的一个范围的值

时间:2014-04-17 09:31:07

标签: excel-vba vba excel

尝试运行以下代码,调试器在第temprow = rgSkalaD.Find(element.Value).Row行停止,给出错误

  

运行时错误'91'对象变量或未设置块变量?

我不知道为什么。将鼠标悬停在temprow上,它会显示正确的值。谁能在这帮助我。

sub test()
Set rgSkalaV = ThisWorkbook.Worksheets(1).Range("B1:B700")
Set rgSkalaD = ThisWorkbook.Worksheets(1).Range("A1:A700")

Dim element As Range
For Each element In rgSkalaV
    Dim temprow As Long
    temprow = rgSkalaD.Find(element.Value).Row
    ThisWorkbook.Worksheets(1).Cells(temprow, rSIf) = THisWorkbook.Worksheets(2).Cells(element.Row, 5)
Next element

End Sub

代码的作用: 我想在范围2中找到范围1中的每个元素。如果我找到值,我想从第一个Range + 5列中复制除此值旁边的几列。

1 个答案:

答案 0 :(得分:0)

尝试更改您的代码:

Sub test()
    Set rgSkalaV = ThisWorkbook.Worksheets(1).Range("B1:B7")
    Set rgSkalaD = ThisWorkbook.Worksheets(1).Range("A1:A7")

    Dim TempRng As Range
    Dim element As Range

    For Each element In rgSkalaV
        Set TempRng = rgSkalaD.Find(element.Value)
        If Not TempRng Is Nothing Then
            ThisWorkbook.Worksheets(1).Cells(element.Row, rSIf) = ThisWorkbook.Worksheets(2).Cells(element.Row, 5)
        End If
    Next element
End Sub