首页 > 解决方案 > 使用宏在 Outlook 中发送或接收邮件后在 Excel 中写入日志

问题描述

我需要您的帮助在 Outlook 2010 中创建一个宏,该宏将在从帐户发送任何邮件或在该帐户的收件箱中接收任何邮件后将 From、To、Date、Subject、Flag 存储在 Excel 中。

在那个过程中,我尝试在使用以下代码发送具有一些默认值的邮件后首先在 excel 中创建日志。但它在行给出错误“编译错误,未定义子或函数”:

Windows("Access_Log.xlsx").Activate

代码如下:

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Workbooks.Open FileName:="\\Bmcstr01\grp\SRV\Allsrv\NEW Complaints Logger\GI Complaints\Spreadsheets\Archieve\Access_Log.xlsx"
Windows("Access_Log.xlsx").Activate


'Sheets("log").Activate
If Range("A1").Value = "" Then
n = 1
Else
n = Cells(Rows.Count, "A").End(xlUp).Row + 1
End If
Cells(n, "A").Value = Environ("username")
Cells(n, "b").Value = Date
Cells(n, "c").Value = Time
Cells(n, "d").Value = "Outlook"
Cells(n, "E").Value = "sent mail"
ActiveWorkbook.Save
ActiveWorkbook.Close
End Sub

它是在 ThisOutlookSession --> Application --> SendItem 中编写的。

对此代码和原始要求的任何帮助将不胜感激。

谢谢,弥勒佛

标签: excelvbaloggingoutlook

解决方案


要从 Outlook-VBA 访问 Excel 文件,您首先需要创建一个 Excel 应用程序:

Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")

如果您不希望 Excel 显示使用

xlApp.Visible = False

隐藏它。然后您可以在该应用程序中打开一个 Excel 文件:

Dim xlWb As Object
Set xlWb = xlApp.Workbooks.Open(FileName:="\\Bmcstr01\grp\SRV\Allsrv\NEW Complaints Logger\GI Complaints\Spreadsheets\Archieve\Access_Log.xlsx")

然后您可以访问该文件中的工作表:

Dim xlWs As Object
Set xlWs = xlWb.Worksheets("Sheet1") 'put your sheet name here

然后是您的代码访问此工作表,例如

Const xlUp = -4162 'see explanation below

Dim n As Long
With xlWs
    If .Range("A1").Value = "" Then
        n = 1
    Else
        n = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End If
    .Cells(n, "A").Value = Environ("username")
    .Cells(n, "B").Value = Date
    .Cells(n, "C").Value = Time
    .Cells(n, "D").Value = "Outlook"
    .Cells(n, "E").Value = "sent mail"
End With

xlWb.Close SaveChanges:=True 'close and save workbook

编辑//

请注意,xlUp在 Outlook 中不存在。因此,您需要先使用-4162或定义一个常量,Const xlUp = -4162然后才能使用它。


推荐阅读