2012-07-18 70 views
0

該宏適用於基於特定列中的整數值複製行。我如何獲得它也複製原始數據的格式?重複excel數據的行

Sub DuplicateRows() 

Dim currentRow As Integer 
Dim currentNewSheetRow As Integer: currentNewSheetRow = 1 

For currentRow = 1 To 3 'The last row of your data 

    Dim timesToDuplicate As Integer 
    timesToDuplicate = CInt(Sheet1.Range("D" & currentRow).Value2) 

    Dim i As Integer 
    For i = 1 To timesToDuplicate 

     Sheet2.Range("A" & currentNewSheetRow).Value2 = Sheet1.Range("A" & currentRow).Value2 
     Sheet2.Range("B" & currentNewSheetRow).Value2 = Sheet1.Range("B" & currentRow).Value2 
     Sheet2.Range("C" & currentNewSheetRow).Value2 = Sheet1.Range("C" & currentRow).Value2 

     currentNewSheetRow = currentNewSheetRow + 1 

    Next i 

Next currentRow 

End Sub 
+0

你有什麼試過?你有沒有試過將單元格複製到新行的最明顯的解決方案? – ApplePie 2012-07-18 16:45:02

回答

1

我不太明白你想什麼來完成,但是當我要複製的一切(格式,值等),我用一個細胞的複製和PasteSpecial的功能。

Sub DuplicateRows() 

Dim currentRow As Integer 
Dim currentNewSheetRow As Integer: currentNewSheetRow = 1 

For currentRow = 1 To 3 'The last row of your data 

    Dim timesToDuplicate As Integer 
    timesToDuplicate = CInt(Sheet1.Range("D" & currentRow).Value2) 

    Dim i As Integer 
    For i = 1 To timesToDuplicate 

     Sheet1.Range("A" & currentNewSheetRow).Copy 
     Sheet2.Range("A" & currentRow).PasteSpecial (xlPasteAll) 
     Sheet1.Range("B" & currentNewSheetRow).Copy 
     Sheet2.Range("B" & currentRow).PasteSpecial (xlPasteAll) 
     Sheet1.Range("C" & currentNewSheetRow).Copy 
     Sheet2.Range("C" & currentRow).PasteSpecial (xlPasteAll) 

     currentNewSheetRow = currentNewSheetRow + 1 

    Next i 

Next currentRow 

End Sub 

另請看PasteSpecial函數的posible參數來完成您的結果。