在访问表 VBA 中搜索值

Posted

技术标签:

【中文标题】在访问表 VBA 中搜索值【英文标题】:Searching for a value in Access Table VBA 【发布时间】:2017-01-20 14:36:41 【问题描述】:

我编写了将 excel 文件导入访问表的代码。导入每个文件时,都会记录文件名并将其保存到名为“FilesDownloaded”的单独表中。

我想添加 vba 代码,在导入文件之前它会检查文件名 (myfile) 是否已保存在“FilesDownloaded”表中。这将防止同一个文件被导入两次。

代码:

Function Impo_allExcel()
Dim myfile
Dim mypath
Dim que As Byte
Dim rs As DAO.Recordset


que = MsgBox("This proces will import all excel items with the .xls in the folder C:\MasterCard. Please make sure that only the files you want imported are located in this folder. Do you wish to proceed?", vbYesNo + vbQuestion)
If que = 7 Then
    Exit Function
Else
    'do nothing and proceed with code
End If

DoCmd.SetWarnings (False)

DoCmd.RunSQL "DELETE * FROM tblMaster_Import;"


MsgBox "Please WAIT while we process this request"



mypath = "C:\Master\"
ChDir (mypath)
myfile = Dir(mypath & "*.xls")



Do While myfile <> ""
  If myfile Like "*.xls" Then
     'this will import ALL the excel files
     '(one at a time, but automatically) in this folder.
     ' Make sure that's what you want.
    'DoCmd.TransferSpreadsheet acImport, 8, "tblMasterCard_Import", mypath & myfile
    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel8, "tblMaster_Import", mypath & myfile, 1

    Set rs = CurrentDb.OpenRecordset("FilesDownloaded")
    rs.AddNew
    rs.Fields("Filename").Value = myfile
    rs.Update
    rs.Close
    Set rs = Nothing

  End If
  myfile = Dir()
Loop




'append data to tblAll (risk of duplicates at this point)
DoCmd.RunSQL "INSERT INTO tblAll SELECT tblMaster_Import.* FROM tblMaster_Import;"

DoCmd.OpenQuery "qryUpdateDateField", acViewNormal
''this code will apend to an existing table and runs the risk of doubling data.
DoCmd.SetWarnings (True)

MsgBox "Your upload is complete"

End Function

【问题讨论】:

您要导入的文件有ID吗?也许您可以在表上设置一个主键以避免重复? 【参考方案1】:

一种可能的解决方案是进行查询,它会为您提供表FilesDownloaded 中的行的结果,条件是名称与您的文件相同。像这样的:

countString = "SELECT COUNT(*) FROM [FilesDownloaded] WHERE [NAMEOFCOL] = " & myFile

然后运行查询,如果结果大于1,你显然有。

【讨论】:

我输入的代码为:Do While myfile "" countString = "Select Count() From [FilesDownloaded] Where [Filename] = myfile" If myfile Like ". xls" And countString = 0 然后我收到不匹配的错误消息。帮忙? 您应该运行查询并获得结果。看看***.com/questions/23992226/…和msdn.microsoft.com/en-us/library/office/ff194626.aspx

以上是关于在访问表 VBA 中搜索值的主要内容,如果未能解决你的问题,请参考以下文章

从访问 vba 中的多值组合框中获取值

从vba中的表填充列表框

访问 VBA 代码以删除表(如果存在)

使用 VBA 未打开表单时在访问中更新表单

VBA和IE8-输入值并进行搜索

如何通过vba查看访问表中的记录集?