2011-12-23 109 views
0

我有3個Excel工作表列如下:使用Excel VBA複製粘貼行很簡單嗎?

Sheet1 
ColA ColB 
5  4 
5  5 
45  56 
56  56 

Sheet2 
ColA ColB 
53  24 
55  55 

Sheet3 
ColA ColB 
45  56 
56  56 
3  4 

我要粘貼列從表2和3複製到表1,我不知道該行的數字,因爲它們能夠基於數據。

任何人都可以告訴我這個宏代碼,而不必確定Excel表中的最後一個數據行。

我真的很感激你的建議。

回答

1

如果您只是想要移動這些值,以下是您正在處理的內容。如果您想要移動格式,請詢問。

Sub CopyToSheet1() 

    Dim Row1Max As Long 
    Dim Row1Next As Long 
    Dim Row23Max As Long 
    Dim Values() As Variant 

    ' Find bottom rows of sheets 1 and 2 
    ' These statements position a virtual cursor to the bottom of column 1 
    ' and then move up until they find data. For Sheet 1 it adds one because 
    ' it needs the first blank row 
    Row1Next = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row + 1 
    Row23Max = Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row 
    ' Extract data from sheet 2 
    Values = Worksheets("Sheet2").Range("A1:B" & Row23Max).Value 
    ' Drop into sheet 1 
    Row1Max = Row1Next + Row23Max - 1 
    Worksheets("Sheet1").Range("A" & Row1Next & ":B" & Row1Max).Value = Values 
    Row1Next = Row1Max + 1 
    ' Find bottom row of sheet3 
    Row23Max = Worksheets("Sheet3").Cells(Rows.Count, 1).End(xlUp).Row 
    ' Extract data from sheet 3 
    Values = Worksheets("Sheet3").Range("A1:B" & Row23Max).Value 
    ' Drop into sheet 1 
    Row1Max = Row1Next + Row23Max - 1 
    Worksheets("Sheet1").Range("A" & Row1Next & ":B" & Row1Max).Value = Values 
    End Sub 
0

我經常使用的功能

Function CountRows(r as Range) As Long 
    CountRows = r.Worksheet.Range(r,r.End(xlDown)).Rows.Count 
End Function 

然後複製並粘貼

Sub CopyRange(r_src as Range, r_dst as Range, numrows as Long, numcols as Long) 
    r_dst.Resize(numrows,numcols).Value2 = r_src.Resize(numrows,numcols).Value2 
End Dub 

你使用這樣

Dim N as Long 
Dim r_dst as Range, r_src as Range 
' Pick first cell on sheet 1 
Set r_dst = Sheet1.Range("A1") 
' Count existing data and move to end 
N = CountRows(r_dst) 
Set r_dst = r_dst.Offset(N,0) 
' Pick first cell of sheet 2 and count rows 
Set r_src = Sheet2.Range("A1") 
N = CountRows(r_src) 
' Copy rows to sheet 1 
CopyRange r_src, r_dst, N, 2 
' Move to end of data on sheet 1 
Set r_dst = r_dst.Offset(N,0) 
' Pick first cell on sheet 2 and count rows 
Set r_src = Sheet3.Range("A1") 
N = CountRows(r_src) 
' Copy rows to sheet 1 
CopyRange r_src, r_dst, N, 2