希望有人可以帮我为我编写脚本
我正在尝试使用附加到按钮的宏创建一个excel文件,该按钮将数据导出到sql。 我的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中创建宏时,我的代码如下
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.
有人有任何建议吗?
这就是我的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文件中的数据被删除,我们将每天删除新数据。
答案 0 :(得分:0)
您在查询中提供的日期格式不正确。以下是可接受格式的列表,您需要确保使用的格式符合以下格式:
https://docs.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql
我建议使用Debug.Print "insert int..."
并检查immediates窗口中的格式(在VBExplorer中),然后运行查询
答案 1 :(得分:0)
在您的设计中考虑导出到XML并使用XSLT(或DTD等)创建规则以供SQL导入。 XML可以是在格式之间传递数据的强大方式。
随着数据库和电子表单的更改,此解决方案更具可扩展性。您不必创建更多宏,只需更改XML规则。