我有以下Outlook VBA在电子邮件进来时运行,将在Excel中打开csv文件,复制其中的数据(不包括标题行),打开Access数据库,打开表,删除表行并在完成后粘贴新数据并关闭Access和Excel。
我在几条规则上运行此代码并不断收到91错误代码。
以下代码:
Public Sub CopyPasteIAFeed(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim ExApp As Excel.Application
Dim ExWbk As Workbook
On Error GoTo CopyPasteIAFeed_Error
Set ExApp = CreateObject("Excel.Application")
Set ExWbk = ExApp.Workbooks.Open("C:\Users\" & Environ("UserName") & "\Documents\NCR\Data Feeds\Report NCR - Daily New Activity Requests.csv")
' Open Feed in Microsoft Excel window.
ExApp.Visible = True
ExApp.ScreenUpdating = True
ExApp.ActiveSheet.Range("A2").Select
ExApp.ActiveSheet.Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
Dim oApp As Access.Application
Dim LPath As String
LPath = "C:\Users\" & Environ("UserName") & "\Documents\NCR\Database\SP - Link to KM - Non-Critical Request Repository.accdb"
Set oApp = CreateObject("Access.Application")
' Open database in Microsoft Access window.
oApp.OpenCurrentDatabase LPath
oApp.Visible = True
oApp.DoCmd.OpenTable "ReportNCRDailyNewActivity", acViewNormal, acEdit
oApp.DoCmd.RunSQL "DELETE * FROM ReportNCRDailyNewActivity"
oApp.DoCmd.RunCommand acCmdPasteAppend
oApp.CloseCurrentDatabase
oApp.Quit acQuitSaveAll
ExApp.CutCopyMode = False
ExApp.Quit
Set objAtt = Nothing
Set oApp = Nothing
Set ExApp = Nothing
MsgBox "InStream Activity Feed Imported. Continue"
On Error GoTo 0
Exit Sub
CopyPasteIAFeed_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure CopyPasteIAFeed of Module Module10"
End Sub
答案 0 :(得分:1)
无需使用Excel,因为MS Access可以使用DoCmd.TransferText充分上传csv文件。
...
Dim oApp As Access.Application
Dim LPath As String
LPath = "C:\Users\" & Environ("UserName") & "\Documents\NCR\Database\SP - Link to KM - Non-Critical Request Repository.accdb"
Set oApp = CreateObject("Access.Application")
' Open database in Microsoft Access window.
oApp.OpenCurrentDatabase LPath
oApp.DoCmd.RunSQL "DELETE * FROM ReportNCRDailyNewActivity"
oApp.DoCmd.TransferText acImportDelim, , "ReportNCRDailyNewActivity", LPath, True
oApp.CloseCurrentDatabase
oApp.Quit
...
除此之外,Access默认使用Jet / ACE SQL Engine发布,并且可以迁移并连接到其他关系数据库管理系统(RDMS)。考虑使用这个强大的软件作为任何数据迁移需求的中心点。作为数据库客户端,它可以处理各种文件类型:csv,txt,tab,xlsx,sql,xml,甚至html和ODBC / OLEDB源。因此,您的Outlook宏将很好地成为Access VBA模块!