2013-04-18 52 views
0

我目前使用的設置如下。將Excel擴展表導出到具有時間戳的訪問表?

Set AccessConn = CreateObject("ADODB.Connection") 

sExcel = "[Excel 8.0;HDR=YES;IMEX=2;DATABASE=" & ThisWorkbook.FullName & "].[Sheet1$]" 

AccessConn.Open "DSN=Foo", "", "" 


sSQL = "Insert Into BarTable Select * FROM " + sExcel 


AccessConn.Execute sSQL 

現在,如果我想在導出中添加一個now()列,這有可能嗎?像

Set AccessConn = CreateObject("ADODB.Connection") 

sExcel = "[Excel 8.0;HDR=YES;IMEX=2;DATABASE=" & ThisWorkbook.FullName & "].[Sheet1$]" 

AccessConn.Open "DSN=Foo", "", "" 


sSQL = "Insert Into BarTable Select *,NOW() FROM " + sExcel 


AccessConn.Execute sSQL 

BarTable中的最後一列是日期/時間列,我想插入當前時間?

回答

0

要在SQL中輸入日期,您可能需要將其轉換爲文本 - Access本身可以處理'Now()',但不知道它是否可以在傳遞SQL字符串時使用。像下面的東西應該這樣做。

sSQL = "Insert Into BarTable Select *,#" & format(NOW(),"MM/DD/YYYY hh:mm:ss") & "# As DateTimeStamp FROM " + sExcel 

在訪問我有用來構建SQL字符串時,我沒有測試過,但他們應該轉換到Excel VBA沒關係得到的日期或日期和時間標記兩個功能:

Function MakeSQLDateTime(pSourceDate As Variant) As String 
    Dim SQLDay As String, SQLMonth As String, SQLYear As String, SQLTime As String 


    SQLDay = Day(pSourceDate) 
    SQLMonth = Month(pSourceDate) 
    SQLYear = Right(Year(pSourceDate), 4) 
    SQLTime = Hour(pSourceDate) & ":" & Minute(pSourceDate) & ":" & Second(pSourceDate) 
    MakeSQLDateTime = "#" & SQLMonth & "/" & SQLDay & "/" & SQLYear & " " & SQLTime & "#" 
End Function 

Function MakeSQLDate(pSourceDate As Variant) As String 
    Dim SQLDay As String 
    Dim SQLMonth As String 
    Dim SQLYear As String 

    SQLDay = Day(pSourceDate) 
    SQLMonth = Month(pSourceDate) 
    SQLYear = Right(Year(pSourceDate), 4) 
    MakeSQLDate = "#" & SQLMonth & "/" & SQLDay & "/" & SQLYear & "#" 
End Function 

使用這些來完成您所嘗試的操作:

sSQL = "Insert Into BarTable Select *," & makeSQLDateTime(Now()) & " As DateTimeStamp FROM " + sExcel