将变量名的每日文件导入access数据库



如果有人提出这个问题而我忽略了,请允许我提前道歉。我花了好几天的时间在这上面,但还是不能让它100%运行。

我正试图导入一个excel文件,每天早上通过电子邮件发送到一个访问数据库。该文件的日期部分每天都在变化。每天的命名模式都是"FTTQ m-dd-yyyy"。文件名中显示的日期为上一个工作日,例如,8/24的FTTQ在8/25收到邮件。下面的代码是我到目前为止所拥有的,它将循环遍历文件夹,但是当它到达正确的日期时,它找不到它。我已经尝试了几个变化,但访问不断崩溃,当我试图运行它。理想情况下,我需要访问找到文件上的最新日期并导入它,例如周一进来并获得周五/周六的文件,或者在一周内获得前一天的文件。任何帮助都将不胜感激。

Private Sub Button1_Click()
Dim strToday As String
Dim strFilePath as String
Dim strFile as String
strToday = Format(Date, "m-dd-yyyy")
strFilePath = "C:Userscole.strattonDocumentsProcurementFTTQ 'Note:FTTQ is the beginning of the file name
strFile = Dir(strFilePath, "*.xlsx")
  Do While strFile <> ""
    If Right(strFile,14) = strToday & ".xlsx" Then
      DoCmd.TransferSpreadsheet, acImport, "tblTest",strFile, True
    End If
  strFile = Dir 'Note: I do not understand the point of this line or what it does or supposed to do.
  Loop
End Sub

要找到最新的现有文件,我将像这样更改循环:

Dim searchDate As Date
Dim strDate As String
Dim strFilePath As String
Dim strFile As String
Dim i As Long
' Search backwards from today for a file with the date name
For i = 0 To -7 Step -1
    searchDate = DateAdd("d", i, Date)
    strDate = Format(searchDate, "m-dd-yyyy")
    strFilePath = "C:Userscole.strattonDocumentsProcurementFTTQ " & strDate & ".xlsx"
    Debug.Print "Looking for: " & strFilePath 
    ' Check if file exists
    strFile = Dir(strFilePath)
    If strFile <> "" Then
        ' Note that Dir() only returns the file name, so use strFilePath
        DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "tblTest", strFilePath, True
        ' file found, exit loop
        Exit For
    End If
Next i

***我假设您在实际代码中的strFilePath行中有关闭"。* * * *

这一行看起来像问题…

strFile = Dir(strFilePath, "*.xlsx")

本页将向您展示使用Dir的正确语法…http://www.techonthenet.com/excel/formulas/dir.php

strFile = Dir(strFilePath & "*.xlsx") <——你把文件扩展名放在了属性应该去的地方。

然而,你也需要改变你的日期。如果文件上有昨天的日期,而不是今天的……strToday = Format(Date-1, "m-dd-yyyy")

这条线…strFile = Dir

将字符串设置为下一个符合搜索条件的文件名。

最新更新