簡體   English   中英

將特定列從excel工作表復制到另一個工作表

[英]Copy specific columns from excel worksheet to another worksheet

我是excel編碼的新手,我想知道是否有人可以幫助我解決這個小問題。 我有一個具有兩個工作表Data_1和Data_2的excel工作簿,我需要的是某種VBA代碼,可以將數據從Data_1工作表復制到Data_2工作表,但是我需要從Data_1中訪問的唯一列是A,B,E,G, I,J,L,M,而不會覆蓋data_2上的先前數據,因為該數據每天都會更新。 這是可以做到的嗎?

復制數據可以像這樣完成:

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

問題是,這將覆蓋之前的條目,因此您每次都必須更改范圍。

若要避免每次嘗試這樣做,請嘗試以下方法: 選擇“不同的列范圍Excel VBA”並每次增加列的值(以將其粘貼到其他單元格中)

我希望這會有所幫助,如果不是,請發表評論:)

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM