我有一个Access VBA脚本
我想再补充一步:
Field1
中的Excel值与Access表Exclude
中的值列表进行比较,如果找到匹配项,则删除Excel中的整行。这是简化的代码,附有说明新代码应该去的地方的注释:
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM FileList")
rs.MoveFirst
Dim appExcel As Excel.Application
Set appExcel = New Excel.Application
Dim objWorkbook As Excel.Workbook
Dim objSheet As Excel.Worksheet
Do Until rs.EOF = True
strFilePath = rs!FilePath
Set objWorkbook = appExcel.Workbooks.Open(strFilePath)
For Each objSheet In objWorkbook.Sheets
objSheet.Select
strQuery =
"INSERT INTO tblImport (Field1)
SELECT [Field1]
FROM [Excel 8.0;HDR=YES;DATABASE=" & strFilePath & "].[" & objSheet.Name & strRange & "]"
CurrentDb.Execute strQuery, dbFailOnError
***Add Code Here to Delete Rows in Excel where value found in Exclusion table***
Next objSheet
Set objSheet = Nothing
objWorkbook.SaveAs FileName:=strFilePath, FileFormat:=xlExcel8
objWorkbook.Close SaveChanges:=False
Set objWorkbook = Nothing
rs.MoveNext
Loop
我确定我需要对另一个RecordSet进行Dim:
Dim rsExclude AS Recordset
Set rsExclude = CurrentDb.OpenRecordset("SELECT * FROM Exclude")
那么什么?或者也许有人可以推荐一种替代方法?
答案 0 :(得分:1)
好的,我想出了一个解决方案。我并不是说它是“最优的”(我希望使用基于Set的解决方案,而不是这种迭代解决方案),但它的工作速度非常快。基本上,我添加了一个执行以下操作的Do-While循环:
添加以下代码:
Do While intRow <= strLastRow
If IsNull(DLookup("Field1", "Exclude", "Field1 = '" & objSheet.Range("A" & intRow).Value & "'")) Then
intRow = intRow + 1 'No match, move to next row
Else
objSheet.Rows(intRow).Delete 'Match found, delete row
strLastRow = strLastRow - 1 'Decrease the number of rows in range
End If
Loop
答案 1 :(得分:0)
另一种方法是使用Exclude表作为条件在Access中创建Delete查询。然后在导入所有电子表格后从代码中执行查询(没有理由在每个电子表格后运行它并减慢宏的速度)。
或者只是修改您的插入查询以便为您执行此操作...
"INSERT INTO tblImport (Field1)
SELECT [Field1]
FROM [Excel 8.0;HDR=YES;DATABASE=" & strFilePath & "].[" & objSheet.Name & strRange & "]
WHERE [Field1] NOT IN (SELECT [yourFieldInExclusion] FROM Exclusion)"