简体   繁体   English

导入附加vba MS-Access

[英]Import append vba MS-Access

Need help with the Access VBA I am trying to import spreadsheets from excel into access. 在Access VBA中需要帮助我正在尝试将电子表格从excel导入到access中。 Once it is imported it will be appended into a different table and the import table will be deleted so that i can then import a new spreadsheet. 一旦导入,它将被追加到另一个表中,并且导入表将被删除,这样我就可以导入新的电子表格了。 However i have error when appending i need to append the entire table because i will not always know the header from the spreadsheet and how many their are. 但是我在追加时出现错误,我需要追加整个表,因为我将不总是知道电子表格的标题以及它们的数量。 Please Help. 请帮忙。 Below is the code i have been work on. 下面是我一直在努力的代码。

Module- 模块-

Option Compare Database

Function selectFile()
Dim fd As FileDialog, fileName As String

On Error GoTo ErrorHandler

Set fd = Application.FileDialog(msoFileDialogFilePicker)

fd.AllowMultiSelect = False

If fd.Show = True Then
    If fd.SelectedItems(1) <> vbNullString Then
        fileName = fd.SelectedItems(1)
    End If
Else
    'Exit code if no file is selected
    End
End If

'Return Selected FileName
selectFile = fileName

Set fd = Nothing

Exit Function

ErrorHandler:
Set fd = Nothing
MsgBox "Error " & Err & ": " & Error(Err)

End Function

VBA - VBA-

Private Sub cmdImportNoDelete_Click()
'Unset warnings
DoCmd.SetWarnings False

'Import spreadsheet
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Import", selectFile, True

'SQL append statement, Needs to append entire table (must be able to append multiply table with different headers
DoCmd.RunSQL "INSERT INTO Tbl_ImportDump * FROM Import"

'SQL delete Table
DoCmd.DeleteObject acTable, "Import"


DoCmd.SetWarnings True
End Sub

Tbl_ImportDump must exist. Tbl_ImportDump必须存在。 If it doesn't already, create it: 如果尚未创建,请创建它:

DoCmd.RunSQL _
    "CREATE TABLE Tbl_ImportDump (Col1 Col1DataType, Col2 Col2DataType, etc)"

Then after importing your spreadsheet (as table Import, as you've already done), get the column names in the Import table, and put these into the insert statement: 然后,在导入电子表格后(如已完成,作为表Import),在Import表中获取列名,并将其放入insert语句中:

dim ImportCols as String: ImportCols = ""
dim ii as long
dim rs as Recordset

rs.OpenRecordset "SELECT TOP 1 * FROM Import"
for ii = 0 to 2
    ImportCols = ImportCols & "," & rs.Fields(0).Name
next
importCols = mid(importCols, 2)

DoCmd.RunSQL _
    "INSERT INTO Tbl_ImportDump (Col1, Col2, Col3) " & _
    "SELECT " & importCols & " FROM Import"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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