【问题标题】:Importing Data from Access into Excel weekly using ADO每周使用 ADO 将数据从 Access 导入 Excel
【发布时间】:2019-10-29 14:55:02
【问题描述】:

我正在尝试使用 ADO 将数据从 Access 自动提取到 Excel。每周我都会从周一到周五提取前几周的交易。现在我有 SQL 提取前一周的交易,但是我现在的方式是我必须每周手动更改代码中的日期。有没有办法自动做到这一点?

以下是我目前拥有的代码:

Sub Import()
  'Declaring the necessary variables
  Dim cn As ADODB.Connection
  Dim rs As ADODB.Recordset
  Dim dbPath As String
  Dim SQL As String
  Dim i As Integer
  Dim var As Range

  cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
  "Data Source=xxx"

  'create the SQL statement to retrieve the data from the table
  sSQL = "SELECT * FROM BP_Closed_Deals WHERE Start_Date between '10/21/2019' and '10/25/2019'"

  'create the ADODB recordset object
  Set rs = New ADODB.Recordset

  'connectionString open
  rs.Open sSQL, cn, adOpenForwardOnly, adLockReadOnly, adCmdText

  If Not rsData.EOF Then
      Sheets("Deals_2018_Copy").Range("A2").CopyFromRecordset rsData
      rsData.Close

       Else
       rsData.Close
       MsgBox "Error: No records returned", vbCritical
   End If

   Set rsData = Nothing


  End Sub

【问题讨论】:

  • 你只需要改变你的SQL,比如">=" & Date()-7 & "或者类似的东西。网上会有很多关于在 SQL 中使用日期的资料,这会有所帮助。然后,您可以使用各种技术找到最后一行并粘贴到那里。
  • 如果 Start_Date 是日期时间字段,则此查询在 MS Access 中无法工作,因为日期不允许引用字符串。
  • 尝试先改变两件事 cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _ "Data Source=C:\myFolder\myAccessFile.accdb" 另一个是 sSQL = "SELECT * FROM BP_Closed_Deals WHERE Start_Date between #10/21/2019# and #10/25/2019#"

标签: excel vba ms-access ado


【解决方案1】:

考虑使用DatePart 查找相对于今天的上周一和周五的日期:

 sSQL = "SELECT * FROM BP_Closed_Deals "_
         & "WHERE Start_Date BETWEEN Date() - (DatePart('d', Date()) - 2) - 7" _
         & "                     AND Date() - (DatePart('d', Date()) - 2) - 3"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 2010-12-04
    相关资源
    最近更新 更多