Is this simple to copy pasting rows with Excel VBA?

被刻印的时光 ゝ 提交于 2019-12-25 03:37:07

问题


I have columns in 3 excel sheets like this:

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

I want to copy paste columns from sheet 2 and 3 to sheet 1 and I am not sure of the row numbers as they can change based on the data.

Can anyone tell me the macro code to this without being sure of last data row in excel sheet.

I would really appreciate your suggestion.


回答1:


If you just want to move the values, the following is what you are after. If you want to move the formatting as well, ask.

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



回答2:


I have often used a function

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

Then to copy and paste

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

Which you use it like this

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


来源:https://stackoverflow.com/questions/8618531/is-this-simple-to-copy-pasting-rows-with-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!