Excel VBA从单元格插入到sql表中的date – 默认为1900-01-01
美好的一天,
我正在用这个东西把我的头撞在桌子上。 我可以通过Excel VBA更新SQL表格,但date不会正确通过。 值总是通过1900-01-01或者在我已经使用1900-01-28显示的格式的某些情况下。
这是一个简单的testing设置。 1表格有2列CellText和CellDate,都从单元格区域获取它们的值。
CellText的预期值是“Some Text”CellDate的预期值是24/03/2015
这是我的代码:
Sub UpdateTable() Dim cnn As ADODB.Connection Dim uSQL As String Dim strText As String Dim strDate As Date strText = ActiveSheet.Range("b4").Value strDate = Format(ActiveSheet.Range("c4").Value, "dd/mm/yyyy") Set cnn = New Connection cnnstr = "Provider=SQLOLEDB; " & _ "Data Source=ServerName; " & _ "Initial Catalog=DbName;" & _ "User ID=UserName;" & _ "Trusted_Connection=Yes;" cnn.Open cnnstr uSQL = "INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('" & strText & "', " & strDate & ")" Debug.Print uSQL cnn.Execute uSQL cnn.Close Set cnn = Nothing Exit Sub End Sub
我的debugging值是这样的INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('Some Text ', 24/03/2015)
表格中的我的CellDate格式是datetime。
任何人都可以摆脱灯吗?
亲切的问候恐龙
看起来你在date的任何一边都缺less单引号。
INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('Some Text ', 24/03/2015)
应该
INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('Some Text ', '24/03/2015')
使用CDate函数将string格式化的date转换为datetypes
Sub UpdateTable() Dim cnn As ADODB.Connection Dim uSQL As String Dim strText As String Dim strDate As Date strText = ActiveSheet.Range("b4").Value strDate = Format(ActiveSheet.Range("c4").Value, "dd/mm/yyyy") Set cnn = New Connection cnnstr = "Provider=SQLOLEDB; " & _ "Data Source=ServerName; " & _ "Initial Catalog=DbName;" & _ "User ID=UserName;" & _ "Trusted_Connection=Yes;" cnn.Open cnnstr uSQL = "INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('" & strText & "', " & CDate(strDate) & ")" Debug.Print uSQL cnn.Execute uSQL cnn.Close Set cnn = Nothing Exit Sub End Sub