搜索并从另一个工作表复制

时间:2019-03-08 12:24:47

标签: excel vba for-loop

我正在尝试创建一个功能,该功能基于一个工作表中的数据将搜索另一个工作表以进行比较,然后将其复制到第一个工作表中。

这是我的功能:

Sub kopiuj()
    Dim row As Long
    Dim copyRng As Range, pasteRng As Range

    row = 7
    If IsEmpty(Cells(row, 3)) Then
        MsgBox "Error1"
        Exit Sub
    End If
    Do Until IsEmpty(Cells(row, 3))
     If IsEmpty(Cells(row, 6)) And Cells(row, 5) = "cond" Then
          MsgBox "Error2"
           Exit Sub
     End If
     copyRng = szukaj2(Cells(row, 5).Value, Cells(row, 6).Value)
     Set pasteRng = Range(Cells(row, 8), Cells(row, 25))
     copyRng.Copy pasteRng
     row = row + 1
    Loop

End Sub

Function szukaj2(ByVal pp As String, ByVal p As String) As Range
  Dim PN As Worksheet
  Dim row As Integer
  Set PN = ActiveWorkbook.Sheets("PN")

  If pp <> "cond1" And pp <> "cond2" Then pp = "sth"
  For row = 7 To PN.Cells(Rows.Count, 4).End(xlUp).row Step 1
   If StrComp(pp, PN.Cells(row, 3).Value, vbTextCompare) = 0 And StrComp(p, PN.Cells(row, 1).Value, vbTextCompare) = 0 Then
    Set szukaj2 = PN.Range(PN.Cells(row, 8), PN.Cells(row, 25))
    Exit For
   End If
  Next
End Function

我收到错误91

  

运行时错误“未设置对象变量或带块变量”

1 个答案:

答案 0 :(得分:0)

您的错误将出现在此代码行

class ContainsVariable {

  var variable = 1;

}

class DoesNotContainVariable {

  var useVariable = variable + 1; // This gives me an error saying:
                                  // Undefined name 'variable' 

}

您需要将Set与对象变量一起使用。将此代码行更改为:

copyRng = szukaj2(Cells(row, 5).Value, Cells(row, 6).Value)

那应该可以正常工作。