2011-12-23 107 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