简体   繁体   中英

Uploading Date Column to ms access from excel using sql vba

I am trying to upload all the columns in excel sheet to msaccess using sql with adodb. Everything works fine except the date columns where some of the rows will have blanks. Suppose If i wanted to upload 5 rows to ms access from excel sheet and any of the date column is blank in the first row, then its throwing me an data type mismatch error. but if i sort the date column in excel by rows with dates being top and blanks being bottom and if i try to upload, it uploads fine.

So my concern is ms access considering the column datatype based on the first row value in excel, even though i declared as proper data type in ms access.

Here is the code i am using

Public Sub Upload_Data_from_excel()
Set cn = CreateObject("ADODB.Connection")
dbPath = ThisWorkbook.Path & "\db.accdb"
dbWb = ThisWorkbook.FullName
dbWs_shtname = "SHEET1"
tbl_name = "TBL_EXCEL_DATA"
scn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath & ";Jet OLEDB:Database Password=123456"
cn.Open scn

' Delete existing records
ssql = "DELETE * FROM " & tbl_name
cn.Execute ssql

dsh = "[" & dbWs_shtname & "$]"
ssql = "INSERT INTO " & tbl_name & " "
ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
cn.Execute ssql
Set cn = Nothing
Application.StatusBar = ""

End Sub

在此处输入图片说明

any support is much appreciated

Developers often try to re-write functionality that's already built-in to Access (via either a UI or VBA functions), and as far as I can tell that's the case here.

One line of code will handle your import, including flexibility with issues like you describe.

This code:

DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, _
    "TBL_EXCEL_DATA", "C:\tmp-xlimport.xlsm", True, "SHEET1!A:B"

...worked fine for me, error-free, like this:

屏幕截图示例

...and would replace all of your code except for deleting the existing records -- which, personally, I use the clean & simple:

DoCmd.RunSQL ("DELETE FROM TBL_EXCEL_DATA")

...or to avoid the " x records will be deleted " warning:

DoCmd.SetWarnings False
DoCmd.RunSQL ("DELETE FROM TBL_EXCEL_DATA")
DoCmd.SetWarnings True

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