代码之家  ›  专栏  ›  技术社区  ›  anky

在accessvba中动态删除for循环中每个表中的一行

  •  0
  • anky  · 技术社区  · 6 年前

    我正在尝试将文件夹中的excel文件与access数据库中的表(与我的excel文件同名)匹配,并尝试导入excel中的数据以进行访问。

    Sub import()
    
    Dim blnHasFieldNames As Boolean
    Dim strWorksheet As String, strTable As String
    Dim strPath As String, strPathFile As String
    
    blnHasFieldNames = True
    
    
    strPath = "D:\PersonalData\working_table\"
    
    strWorksheet = "Sheet1"
    
    ' Import the data from each workbook file in the folder
    strFile = Dir(strPath & "*.xlsx")
    Do While Len(strFile) > 0
          strPathFile = strPath & strFile
          strTable = Left(strFile, InStrRev(strFile, ".xlsx") - 1)
    
          DoCmd.TransferSpreadsheet acImport, _
                acSpreadsheetTypeExcel9, strTable, strPathFile, _
                blnHasFieldNames, strWorksheet & "$"
    
          DoCmd.RunSQL ("DELETE * FROM " & strTable & " WHERE SPEC_ID = 'Specification ID'")
    
    
    
          strFile = Dir()
    Loop
    
    
    
    End Sub
    

    SPEC_ID = 'Specification ID' . 我在线路上遇到一个错误:

    DoCmd.RunSQL ("DELETE * FROM " & strTable & " WHERE SPEC_ID = 'Specification ID'")
    

    其中规定:

    运行时错误:“3131” FROM子句语法错误。

    请告诉我我做错了什么。

    提前谢谢。

    2 回复  |  直到 6 年前
        1
  •  2
  •   HansUp    6 年前

    使用 DoCmd.SetWarnings 是制造麻烦的方法。如果sql中有一个错误,并且您的代码在没有将警告设置回true的情况下退出,该怎么办?各种奇怪的事情发生了。取而代之的是使用更简单和同样简单的方法

    CurrentDb.Execute "DELETE * FROM [" & strTable & "] WHERE SPEC_ID = 'Specification ID'"
    

    你仍然需要检查strTable没有 [ ] 在名称中(否则括号将无效),您需要删除或转义它们(取决于实际表的命名方式)。

        2
  •  0
  •   Tarun. P    6 年前

    Docmd.SetWarnings False
    
    DoCmd.RunSQL ("DELETE * FROM [" & strTable & "] WHERE SPEC_ID = 'Specification ID'")
    
    Docmd.SetWarnings True