【发布时间】:2017-10-07 16:59:54
【问题描述】:
我有一个 VBA,可以将电子邮件从 Outlook 写入 Excel。但是,我希望此 Excel 表保持打开状态。目前我已经让工作表保持打开状态(并且只是在电子邮件进入后保存),但是每次我在我的工作簿中收到一封新电子邮件时,它都会要求我重新打开工作簿,因为 VBA 是告诉它打开工作簿。
代码如下:
Sub ExportToExcel(MyMail As MailItem)
Dim strID As String, olNS As Outlook.NameSpace
Dim olMail As Outlook.MailItem
Dim strFileName As String
'~~> Excel Variables
Dim oXLApp As Object, oXLwb As Object, oXLws As Object
Dim lRow As Long, fRow As Long
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set olMail = olNS.GetItemFromID(strID)
'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
'~~> Show Excel
oXLApp.Visible = True
'~~> Open the relevant file
Set oXLwb = oXLApp.Workbooks.Open("\\C:\Rachael\VBAs\Control Panels.xlsm")
'~~> Set the relevant output sheet. Change as applicable
Set oXLws = oXLwb.Sheets("Ash Data")
'~~> Write to outlook
With oXLws
'~~> Code here to output data from email to Excel File
'~~> For example
'* insert into last row (old alternative)
'* you can remove this and the declare of lRow (at the top) if you don't need the old last row insert anymore.
'lRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1 'next new row
'.Range("A" & lRow).Value = olMail.Body 'write into last row
'* insert into first row
fRow = 1 'first row
.Rows(fRow).Insert Shift:=xlDown
.Range("A" & fRow).Value = olMail.Body 'write into first row
End With
'~~> Close and Clean up Excel
oXLwb.Save
Set oXLws = Nothing
Set oXLwb = Nothing
Set oXLApp = Nothing
Set olMail = Nothing
Set olNS = Nothing
End Sub
我不确定这段代码哪里出了问题,但也许有人知道解决这个问题的方法?
【问题讨论】:
-
下次您使用我们其中一位用户的代码时,至少要提及它并向我们发送该帖子的链接。无论如何,“它要求我重新打开工作簿”,因为您告诉它:
Set oXLwb = oXLApp.Workbooks.Open("\\C:\Rachael\VBAs\Control Panels.xlsm") -
嗨,我认为这是我使用的原件:stackoverflow.com/questions/11876549/… 但我如何更改该行而不是打开它,它只会寻找它,因为这张表将始终保持打开状态?我尝试删除 .open 但它给了我一个错误?
-
在下面看我的答案,看看它对你有用