将特定列从Excel工作表复制到另一个工作表

时间:2016-07-05 23:01:29

标签: excel vba excel-vba

我是excel编码的新手,我想知道是否有人可以帮我解决这个小问题。 我有一个包含两个工作表Data_1和Data_2的Excel工作簿,我需要的是某种类型的VBA代码,可以将数据从Data_1工作表复制到Data_2工作表,但是我需要的唯一一列是Data_1,A,B,E,G, I,J,L,M没有覆盖data_2上的先前数据,因为它将每天更新。 这是可以做到的吗?

2 个答案:

答案 0 :(得分:0)

复制数据可以这样完成:

Sheets("Data_1").Range("A1:A100").Copy _ '100 is just an example
Sheets("Data_2").Range("A1:A100")

问题是,这会覆盖先前的条目,因此您每次都必须更改范围。

每次尝试执行此操作时请尝试以下方法: Select Different Column Range Excel VBA并每次增加列的值(将其粘贴到其他单元格)

我希望这有用,如果不是,只需评论:)

答案 1 :(得分:0)

试试这个:

Sub Demo()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Dim path As String, fileName As String
    Dim lastRowInput As Long, lastRowOutput As Long, rowCntr As Long, lastColumn As Long
    Dim inputWS As Worksheet, outputWS As Worksheet

    'set your sheets here
    Set inputWS = ThisWorkbook.Sheets("Data_1")
    Set outputWS = ThisWorkbook.Sheets("Data_2")
    rowCntr = 1

    'get last rows from both sheets
    lastRowInput = inputWS.Cells(Rows.Count, "A").End(xlUp).Row
    lastRowOutput = outputWS.Cells(Rows.Count, "A").End(xlUp).Row
    lastColumn = inputWS.Cells(1, Columns.Count).End(xlToLeft).Column

    'copy data from columns A, B, E, G, I, J, L and M
    inputWS.Range("A1:B" & lastRowInput).Copy outputWS.Range("A" & lastRowOutput + 1)
    inputWS.Range("E1:E" & lastRowInput).Copy outputWS.Range("E" & lastRowOutput + 1)
    inputWS.Range("G1:G" & lastRowInput).Copy outputWS.Range("G" & lastRowOutput + 1)
    inputWS.Range("I1:J" & lastRowInput).Copy outputWS.Range("I" & lastRowOutput + 1)
    inputWS.Range("L1:M" & lastRowInput).Copy outputWS.Range("L" & lastRowOutput + 1)


    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub

您也可以将值分配给范围:

,而不是复制范围
Range(outputWS.Cells(lastRowOutput + 1, 1), outputWS.Cells(lastRowOutput + lastRowInput, 2)).Value = Range(inputWS.Cells(1, 1), inputWS.Cells(lastRowInput, 2)).Value
Range(outputWS.Cells(lastRowOutput + 1, 5), outputWS.Cells(lastRowOutput + lastRowInput, 5)).Value = Range(inputWS.Cells(1, 5), inputWS.Cells(lastRowInput, 5)).Value
Range(outputWS.Cells(lastRowOutput + 1, 7), outputWS.Cells(lastRowOutput + lastRowInput, 7)).Value = Range(inputWS.Cells(1, 7), inputWS.Cells(lastRowInput, 7)).Value
Range(outputWS.Cells(lastRowOutput + 1, 9), outputWS.Cells(lastRowOutput + lastRowInput, 10)).Value = Range(inputWS.Cells(1, 9), inputWS.Cells(lastRowInput, 10)).Value
Range(outputWS.Cells(lastRowOutput + 1, 12), outputWS.Cells(lastRowOutput + lastRowInput, 13)).Value = Range(inputWS.Cells(1, 12), inputWS.Cells(lastRowInput, 13)).Value