简体   繁体   中英

Import data in certain Excel columns to Access by VBA?

I'm using Access and need to import data from Excel.

The table has too many columns. What I do now is to find every cell I need, merge them, then insert into Access.

Set file = GetObject(path) 'get excel file
intArrNeedCols = Array(3, 4, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 22, 23, 26) 'the columns I need
For row = 2 To file.Sheets(1).UsedRange.Rows.Count  'loop and collect values of each cell in the target column,the first row is title
    strSQL = "INSERT INTO orderlist VALUES("
    For Each col In intArrNeedCols
        strSQL = strSQL & "'" & file.sheets(1).cells(row, col) & "',"
    Next
    '…… 'other statements,like excute sql statement
Next

That is complex and hard to maintain. Is there an easier way?

Consider directly querying from Excel inside MS Access append query which can also be used in DAO/ADO connections. I/O methods like DoCmd.TransferSpreadsheet do not allow selecting specific columns in spreadsheet unless you create a special Excel tab or temp Access table.

In query below adjust named columns accordingly as well as file/sheet name reference. Escape any reserved words, spaces, and special characters with square brackets or backticks.

INSERT INTO OrderList
SELECT t.[Col1], t.[Col2], t.[Col3] ...
FROM [Excel 12.0 Xml;HDR=Yes;Database=C:\Path\To\Excel\File.xlsx].[SHEETNAME$] t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM