2015-12-06 184 views
0

Newbee在這裏既要到這個網站和Excel VBA。我在下面的帖子中使用了RichA的代碼,並且能夠使它適用於我從另一個工作表中填充/複製工作表(Sheet2)上的數據的目的。Excel VBA複製和粘貼循環內的循環 - 限制範圍

代碼鏈接到原始POST Excel VBA Copy and Paste Loop within Loop

我對如何限制範圍爲「命名的範圍」(C13:Z111)的一個問題,而不是在這個「整列」(「C」)碼。我似乎無法讓它限制複製行,從最後一行開始數據並倒數第一行。

我有一些行(C1:C12)的標題在頂部和數據從第13行開始。所以當從一個工作表複製值到'其他'工作表時,頂部的行也複製。我想結束第13行數據的複製。

感謝您的幫助。

這是目前與我無法限制範圍的例外工作。

Sub Generate_Invoice() 

Dim i As Long 
Dim ii As Long 
Dim i3 As Long 
Dim LastRow As Long 
Dim wb As Workbook 
Dim sht1 As Worksheet 
Dim sht2 As Worksheet 

Set wb = ThisWorkbook 
Set sht1 = wb.Sheets("INCENTIVE") 
Set sht2 = wb.Sheets("Sheet2") 

Sheets("Sheet2").Select 
Range("B11:Z200").ClearContents 

'Find the last row (in column C) with data. 
LastRow = sht1.Range("C13:C111").Find("*", searchdirection:=xlPrevious).Row 
ii = 2 

'This is the beginning of the loop >>>This Works BUT BUT BUT goes all the way to the top - REQUESTING HELP WITH CODE ENDS AT ROW 13 AND DOES NOT GO PAST<<< 

For i = 3 To LastRow 
    'First activity 
    sht2.Range("B" & ii) = sht1.Range("C" & i).Value 
    sht2.Range("C" & ii) = sht1.Range("G" & i).Value 
    sht2.Range("D" & ii) = sht1.Range("H" & i).Value 
    sht2.Range("E" & ii) = sht1.Range("P" & i).Value 
    sht2.Range("F" & ii) = sht1.Range("R" & i).Value 
    sht2.Range("G" & ii) = sht1.Range("AD" & i).Value 

    ii = ii + 1 

Next i 

'Return to "Sheet2" 
Sheets("Sheet2").Select 

'Add SUM at bottom of last record in Range"D" 
Dim ws As Worksheet 

    For Each ws In Worksheets 
     With ws.Range("F" & Rows.Count).End(xlUp).Offset(2) 
      .FormulaR1C1 = "=SUM(R11C6:R[-1]C6)" 
      .Offset(, -1).Value = "Total:" 
     End With 
    Next ws 

End Sub 
+0

變化'對於i = 3〜LastRow'到'對於i = 13到LastRow'或變化'II = 2'爲「II = 13' ...不完全其中之一在點,因爲我我有點困惑。 –

回答

0

你只需要退出for循環根據你想要的標準是什麼。例如:

If ii = 13 Then Exit For 
+0

謝謝您的建議。這種改變在第13行停止,因此在代碼範圍內只顯示一條記錄,因爲我們在該範圍內複製。 –

2

您正在查找最後一行,但只查看人口稠密地區。我建議通過在工作表底部開始並在C列中找到最後一個填充的單元格來改變最後一行的確定方法。這將類似於C1048576並點擊Ctrl +

'Find the last row (in column C) with data. 
LastRow = sht1.Cells(Rows.Count, "C").End(xlUp).Row 

'not sure whether you want to reverse this as well 
ii = 2 

'This is the beginning of the loop >>>This Works BUT BUT BUT goes all the way to the top - REQUESTING HELP WITH CODE ENDS AT ROW 13 AND DOES NOT GO PAST<<< 

For i = LastRow To 13 Step -1 'work from the bottom to the top. 
    'First activity 
    sht2.Range("B" & ii) = sht1.Range("C" & i).Value 
    sht2.Range("C" & ii) = sht1.Range("G" & i).Value 
    sht2.Range("D" & ii) = sht1.Range("H" & i).Value 
    sht2.Range("E" & ii) = sht1.Range("P" & i).Value 
    sht2.Range("F" & ii) = sht1.Range("R" & i).Value 
    sht2.Range("G" & ii) = sht1.Range("AD" & i).Value 

    'not sure whether you want to reverse this as well 
    ii = ii + 1 

Next i 
+0

感謝您的快速回答 - 非常感謝。在執行這些更改時,數據按相反順序複製。 Sheet2顯示以最後一個記錄開始和最後一個記錄開始的行。現在C列中的空白行也被複制。數據仍然寫入1-13行。我試圖不復制行1-13行並開始複製有效行13,而不是從第1行開始,理由,標題和指令位於第1-13行。 –