对象变量或With块变量未设置问题

时间:2019-11-30 06:16:34

标签: excel vba object

我在执行多个if条件的循环时遇到问题。我在做什么 1.为“要查找的内容和从何处查找”定义范围和单元格。 2.问题部分:我的If应该分为三级。 -如果x为true,则执行操作,否则为if2 -如果if2为true,则执行操作,否则为if3 -如果是true,那就去做

循环播放下一个

由于某种原因,它运行了好几次,但是随后给了我Object变量或With块变量未设置的信息。我该如何解决..?

错误在线:

If Not cl Is Nothing And Worksheets("Sheet1").Cells(x + 1, 7) = cl.Offset(0, -4) Then

 Sub Question()


Dim lr1 As Long
Dim lr2 As Long
Dim lr3 As Long
Dim lr4 As Long
Dim x As Long, y As Long, n As Integer
Dim arr As Variant, arr2 As Variant
Dim rng As Range, cl As Range
Dim rng2 As Range, c2 As Range


    n = 20 'Start row of Sheet1
    m = 20 'Start row of Sheet2
    o = 20 'Start row of Sheet3

    'Fill the array for a loop in memory
    With Blad6

        lr1 = Worksheets("Sheet4").Cells(.Rows.Count, 1).End(xlUp).Row
        arr = Worksheets("Sheet4").Range("A2:A" & lr1 + 1)
        lr3 = Worksheets("Sheet4").Cells(.Rows.Count, 1).End(xlUp).Row
        arr2 = Worksheets("Sheet4").Range("A2:A" & lr1 + 1)

    End With


    'Get the range to look in
    With Sheet1
        lr2 = Worksheets("Sheet5").Cells(.Rows.Count, 2).End(xlUp).Row
        Set rng = Worksheets("Sheet5").Range("H2:H" & lr2)
    End With


    With Blad6
    'Loop over the array and perform the search

    For x = 1 To UBound(arr)

       Set cl = rng.Find(arr(x, 1), LookIn:=xlValues)
        If Not cl Is Nothing And Worksheets("Sheet1").Cells(x + 1, 7) = cl.Offset(0, -4) Then
            'Things happen here

                n = n + 1

            Else



            If Not cl Is Nothing And Worksheets("").Cells(x + 1, 7) <> cl.Offset(0, -4) And cl.Offset(0, -4) <> 0 And cl.Offset(0, -5) > Worksheets("").Cells(x + 1, 3) Then
           'Things happen here
                m = m + 1

            Else

            If cl Is Nothing Then

              'Things happen here

                o = o + 1

        End If
        End If
        End If

    Next

End With

Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlAutomatic



End Sub

1 个答案:

答案 0 :(得分:0)

VBA评估AND语句的两端,因此,如果cl不为零,它仍会尝试在第二部分使用它(给您一个错误)...

您需要嵌套2个if

If Not cl Is Nothing 
  If Worksheets("Sheet1").Cells(x + 1, 7) = cl.Offset(0, -4) Then
    ' do stuff here if cl is valid and offset condition is met
  Else
    ' do stuff if cl is valid but does not meet the offset condition 
  End If
Else
    ' do something when cl is nothing 
    ' could be the same thing as in above Else
    ' assuming cl is not involved in the operation
End If

如果您使用的是VB.NET,则可以使用AndAlso来代替它,并使其结构更像您拥有它,但事实并非如此。