【问题标题】:Export Excel Spread Sheet to Access Table with A Timestamp?将 Excel 电子表格导出到带有时间戳的访问表?
【发布时间】:2013-04-18 17:05:16
【问题描述】:

我目前使用如下所示的设置。

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 中的最后一列是日期/时间列,我想在其中插入当前时间?

【问题讨论】:

    标签: sql excel adodb insert-into vba


    【解决方案1】:

    要在 SQL 中输入日期,您可能需要将其转换为文本 - Access 本身可以处理“Now()”,但不确定在传递 SQL 字符串时是否可以。像下面这样的东西应该可以做到。

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

    在 Access 中,我有两个函数用于在构建 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 2010-12-23
      • 2014-10-27
      • 1970-01-01
      相关资源
      最近更新 更多