从Access表导出新记录集到指定的Excel工作表
问题描述:
我是VBA新手。所以请耐心等待。 ! 我有共享驱动器上的访问数据库,并且如果表获取新记录,它会自动将记录导出到指定的Excel表。如果有人能为我提供代码,将会有很大的帮助,并给我一点解释。从Access表导出新记录集到指定的Excel工作表
答
访问表本身没有触发机制(至少不是我2003年的古老版本,但我认为新版本有一个)。通常情况下,尽管您将拥有数据输入前端,但您可以将触发器代码放在插入位置。这里有一个例子:
我的朋友一个表:
和这里的数据录入的前端为它:
当我添加一个新朋友的名字,此代码将运行:
'Get the data of the newest record
Set rec = CurrentDb.OpenRecordset("select * from Friends where ID=(select max(ID) from Friends)")
'open Excel
Set excel = CreateObject("Excel.Application")
Set workbook = excel.Workbooks.Open("c:\_a\mySheet.xlsx")
'find the last cell without data
emptyCell = False
rowNum = 1
Do While emptyCell = False
If workbook.Sheets("Sheet1").Cells(rowNum, 1) = "" Then
Exit Do
Else
rowNum = rowNum + 1
End If
Loop
workbook.Sheets("Sheet1").Cells(rowNum, 1).Value = rec.Fields("FriendName")
'save and close the Excel sheet
workbook.Save
workbook.Close
'close the recordset
rec.Close
'quit excel
excel.Quit
现在,当我查看Excel电子表格时,它在单元格的底部添加了记录: