EXCEL VBA应用程序定义或对象定义的错误“1004”

我曾经有一条线

Set rRng1 = Worksheets("Sheet1").Range("I2:J20") 

但是,由于单元格的范围可以从文件到文件(I2是固定的),我发现了一个简单的方法来实现自动化。

范围中的第一个单元总是I2,最后一个单元是J(last_pair_cell)

我认为使用范围(单元格(2,9),单元格(last_pair_cell),10)将诀窍,但我得到错误1004 …

这是整个代码:

 Sub LoopRange2() Dim rCell1 As Range Dim rCell2 As Range Dim rRng1 As Range Dim rRng2 As Range Dim nCol As Integer 'Finds week column to insert values nCol = Worksheets("Clube").Range("P69").Value + 5 'Find number of pairs that played the tournment Dim last_pair_cell As Integer Dim rngX As Range Set rngX = Worksheets("Sheet_CSV").Range("A1:A10000").Find("Board", lookat:=xlPart) If Not rngX Is Nothing Then last_pair_cell = rngX.Row - 1 End If **Set rRng1 = Worksheets("Sheet_CSV").Range(Cells(2, 9), Cells(last_pair_cell, 10))** 'Set rRng1 = Worksheets("Sheet1").Range("I2:J20") Set rRng2 = Worksheets("Clube").Range("C3:C80") 'IF ERROR CHANGE C80 TO C69 For Each rCell1 In rRng1.Cells For Each rCell2 In rRng2.Cells If rCell2.Value = rCell1.Value Then Worksheets("Clube").Cells(rCell2.Row, nCol).Value = Worksheets("Sheet1").Cells(rCell1.Row, 6).Value End If Next rCell2 Next rCell1 End Sub 

您正试图使用Find方法来设置rngX ,在这里:

 Set rngX = Worksheets("Sheet_CSV").Range("A1:A10000").Find("Board", lookat:=xlPart) 

但是,如果您的Find找不到“Board”,那么rngX就是Nothing ,并且您没有通过以下If标准:

 If Not rngX Is Nothing Then last_pair_cell = rngX.Row - 1 End If 

last_pair_cell没有得到rngX.Row - 1的值,而是仍然有默认值0

所以设置您的范围:

 Set rRng1 = Worksheets("Sheet_CSV").Range(Cells(2, 9), Cells(last_pair_cell, 10)) 

将会抛出一个错误,因为Cells(last_pair_cell, 10)实际上是Cells(last_pair_cell, 10) Cells(0, 10) ,这会引发错误。

另外,为了确保你的rRng1是完全合格的,使用正确的语法:

 With Worksheets("Sheet_CSV") Set rRng1 = .Range(.Cells(2, 9), .Cells(last_pair_cell, 10)) End With 

Range内的Cells没有父级工作表。

 Set rRng1 = Worksheets("Sheet_CSV").Range(Worksheets("Sheet_CSV").Cells(2, 9), Worksheets("Sheet_CSV").Cells(last_pair_cell, 10)) 'or more succinctly as, with Worksheets("Sheet_CSV") Set rRng1 =.Range(.Cells(2, 9), .Cells(last_pair_cell, 10)) end with 

看到了。 在.Cells中定义时需要。

为了避免在一次使用Resize()方法之后在父工作表资格之后运行:

 Set rRng1 = Worksheets("Sheet_CSV").Cells(2, 9).Resize(last_pair_cell - 1, 2)