copy from sheet1 cols A,B,C,G,F,R,S,T to sheet 2 in colums A,B,C,D,E,F,G,H

后端 未结 5 697
粉色の甜心
粉色の甜心 2021-01-16 02:25

Excel macro 2016 in VBA. Need to copy from 8 separated columns from one sheet to another, in different order. Tried but the Paste is done always in same column A...

5条回答
  •  误落风尘
    2021-01-16 03:21

    If:

    1. Your data is stored in a file on disk (and not in-memory in an open Excel workbook with unsaved changes), and
    2. You only want to copy and paste the data, not formatting

    then you can read the relevant columns in the appropriate order into an ADODB Recordset, and then copy the recordset data into the destination using the CopyFromRecordset method.

    Add a reference to Microsoft ActiveX Data Objects 6.1 Library (via Tools -> References...). There may be versions other than 6.1; choose the highest.

    Then, you can use the following code:

    Dim excelPath As String
    excelPath = "C:\path\to\excel\file.xlsx" ' Replace with the path to the Excel file
    
    Dim connectionString As String
    connectionString = _
        "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=""" & excelPath & """;" & _
        "Extended Properties=""Excel 12.0;HDR=No"""            
    
    Dim sql As String
    sql = _
        "SELECT F1, F2, F3, F4, F6, F18, F19, F20 " & _
        "FROM [Validation by rules$] "
    ' When setting the HDR=No option in the connection string, column names are
    ' automatically generated -- Column A -> F1, Column B -> F2 etc.
    ' If the first row of your column is the column header, you could specify HDR=Yes
    ' and use those column headers in SQL
    
    Dim rs As New ADODB.Recordset
    rs.Open sql, connectionString
    
    Worksheets("TMP").Range("A1").CopyFromRecordset rs
    

提交回复
热议问题