2017-03-08 79 views
1

我在Sheet2的「TransTypes」動態命名的範圍,我定義爲一個嵌套的循環:通過動態循環命名範圍VBA

=OFFSET(Sheet2!$A$1,0,0,COUNTA(Sheet2!A:A),1) 

和我的循環如下:

Sub Repeat_trans_type() 
    Dim Trans_type_count As Integer, wb As Workbook, wsMain As Worksheet, nwb As Workbook 
    Dim i As Integer, nws As Worksheet, wsSheet2 As Worksheet, j As Integer, cell As Range 
    Dim k As Integer 


    Trans_type_count = Sheet2.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count 

    Application.ScreenUpdating = False 

    Set wb = Workbooks("Book1.xlsm") 
    Set wsMain = wb.Sheets("Sheet1") 
    Set wsSheet2 = wb.Sheets("Sheet2") 

    j = 1 
    k = 1 

Set nwb = Workbooks.Add 
Set nws = nwb.Sheets(1) 

For j = 1 To 96 
     i = 1 
     Set cell = Nothing 
     For Each cell In wsSheet2.Names("TransTypes").RefersToRange.Cells    
     wsMain.Range("A" & j, "C" & j).Copy 
     nws.Range("A" & k).PasteSpecial xlPasteValues 
     nws.Range("A" & k).PasteSpecial xlPasteFormats 
     wsSheet2.Range("A" & i).Copy 
     nws.Range("D" & k).PasteSpecial xlPasteValues 
     nws.Range("D" & k).PasteSpecial xlPasteFormats 
     i = i + 1 
     k = k + 1 
    Next cell 
    Next j 
End Sub 

嵌套循環的第一次迭代工作正常,但在啓動時對第二次執行,即,J = 2,I得到的錯誤消息:

Application-defined or object-defined error 

截至目前,我已通過使用下面的工作:

For Each cell In wsSheet2.Range("A1", wsSheet2.Range("A1").End(xlDown)) 

而不是直接使用指定的範圍。

爲什麼偏移方法不工作的任何想法,將不勝感激。

謝謝。

+0

不知道你對於每一個循環是做什麼的根本就沒有在循環中引用它?你應該發佈你的所有代碼。 – SJR

+0

我已編輯帖子以包含完整的代碼。 – dexterd

+0

好的,通過範圍循環的重點是什麼? – SJR

回答

1

很難說什麼是錯在這裏,但我建議你嘗試以下方法:

  • 使用For Each cell In wsSheet2.Range("TransTypes").Cells在/每

For j = 1 To 96 
    i = 1 
    Set cell = Nothing 
    For Each cell In wsSheet2.Range("TransTypes").Cells 'changed this line (2) 
     wsMain.Range("A" & j, "C" & j).Copy 
     nws.Range("A" & k).PasteSpecial xlPasteValues 
     nws.Range("A" & k).PasteSpecial xlPasteFormats 
     wsSheet2.Range("A" & i).Copy 
     nws.Range("D" & k).PasteSpecial xlPasteValues 
     nws.Range("D" & k).PasteSpecial xlPasteFormats 
     i = i + 1 
     k = k + 1 
    Next cell 
Next j 
+0

謝謝!奇蹟般有效。 – dexterd