2017-03-18 46 views
1

我曾經有一個線EXCEL VBA申請中所定義或對象定義

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

錯誤「1004」,但由於細胞的範圍可從文件改變到文件(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 
+1

在錯誤行之前使用'Debug.print last_pair_cell'來檢查值 – newguy

+0

您聲明'*(I20 is constant is though)*'。你的意思是'I2'還是'J20'? – Jeeped

+0

I2 :)感謝您的注意 –

回答

0

沒有與內RangeCells關聯沒有父表。

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 

Is the . in .Range necessary when defined by .Cells?

1

您正在嘗試使用Find方法來設置rngX,在這裏:

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

但是,如果你的Find沒能找到 「董事會」,然後rngXNothing,並且您未通過以下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(0, 10)它拋出一個錯誤。

而且,只是爲了確保您的rRng1是完全合格的,使用正確的語法:

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

避免第一一個你可以使用Resize()方法後,父母工作合格後運行:

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