使用visual basic将excel导出到sql

希望如果有人能帮助我为这个脚本

我正在试图创build一个macros附加到一个button,将数据导出到SQL的Excel文件。 我的SQL表如下

RecordedPeriod (datetime, not null) EventDate (varchar(8), not null) ID (int, not null) DeptCode (varchar(2), not null) OpCode (varchar(2), not null) StartTime (time(0), not null) FinishTime (time(0), not null) Units (int, not null) 

在Visual Basic for Applications中创buildmacros时,我的代码如下所示

 Sub Button1_Click() Dim conn As New ADODB.Connection Dim iRowNo As Integer Dim sRecordedPeriod, sEventDate, sID, sDeptCode, sOpCode, sStartTime, sFinishTime, sUnits As String With Sheets("Sheet1") 'Open a connection to SQL Server conn.Open "Provider=SQLOLEDB;Data Source=db1\db1;Initial Catalog=ProdTrack;Integrated Security=SSPI;" 'Skip the header row iRowNo = 2 'Loop until empty cell in FirstName Do Until .Cells(iRowNo, 1) = "" sRecordedPeriod = .Cells(iRowNo, 1) sEventDate = .Cells(iRowNo, 2) sID = .Cells(iRowNo, 3) sDeptCode = .Cells(iRowNo, 4) sOpCode = .Cells(iRowNo, 5) sStartTime = .Cells(iRowNo, 6) sFinishTime = .Cells(iRowNo, 7) sUnits = .Cells(iRowNo, 8) 'Generate and execute sql statement to import the excel rows to SQL Server table conn.Execute "insert into dbo.TimeLog (RecordedPeriod, EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) values ('" & sRecordedPeriod & "', '" & sEventDate & "', '" & sID & "', '" & sDeptCode & "', '" & sOpCode & "', '" & sStartTime & "', '" & sFinishTime & "', '" & sUnits & "')" iRowNo = iRowNo + 1 Loop MsgBox "Data Successfully Exported." conn.Close Set conn = Nothing 

导出时收到此错误消息。

  Run-time error '2147217913 (80040e07)': Conversion failed when converting date and/or time from character string. 

有没有人有什么build议?

这是我的excel表的样子。 我试图改变时间格式仍然是一个错误。 我的EventDate是SQL中的一个Varchar,所以应该没有问题。

  RecordedPeriod EventDate ID DeptCode OpCode StartTime FinishTime Units NULL 6/15/2017 45318 DS DS 8:00:00 9:00:00 500 NULL 6/15/2017 45318 DS DS 9:00:00 9:15:00 500 NULL 6/15/2017 45318 DS DS 9:15:00 9:20:00 500 

我们导出到sql后,我的excel文件中的数据被删除,我们每天都会删除新的数据。

您在查询中提供的date格式不正确。 这是一个可接受的格式列表,你需要确保你使用的格式符合这个:

https://docs.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql

我build议使用Debug.Print "insert int..."并检查立即窗口(在VBExplorer)中的格式,然后运行查询

在你的devise中考虑导出到XML,并用XSLT(或DTD等)创build规则以导入SQL。 XML可以成为格式间数据通信的一种强大方式。

添加: https : //docs.microsoft.com/en-us/sql/relational-databases/import-export/examples-of-bulk-import-and-export-of-xml-documents-sql-server

数据库和电子表格更改时,此解决scheme更具可扩展性。 您将不必创build更多的macros,只需要更改XML规则。