从 Outlook 激活打开的 Excel 工作簿



我的Outlook中有一个宏,每当我收到带有特定主题的电子邮件时,它都会自动打开Excel工作簿,并将电子邮件主题的一部分粘贴到其中一个工作表的特定单元格中。它工作得很好。现在我需要执行完全相同的过程,但将此信息粘贴到已打开的工作簿中,而不是打开关闭的文件。

我已经从我有限的 Excel VBA 知识(ActiveWorkbook、worbooks(文件名(.activate 等(中尝试了不同的解决方案,但这些都不起作用,我在网上也没有找到类似的东西,因为大多数宏都是写成从 Excel 文件而不是 Outlook 运行的。

这是我们当前代码的一部分,它打开文件并将电子邮件主题(即"股票代号"值(粘贴到"Lista Empresas"工作表上的特定单元格中。我需要的是一个执行相同操作的代码,但在已经打开的工作簿中(我们称之为"test1"(。

Dim exapp As Excel.Application
Dim ExWbk As Workbook
Dim ExWbk2 As Workbook
Set exapp = New Excel.Application
Set ExWbk2 = exapp.Workbooks.Open("\XXXListaEmpresas_ajustado.xlsm", UpdateLinks:=0)
exapp.Visible = True
ExWbk2.Sheets("Lista Empresas").Range("P2").Value = ticker
ExWbk2.Sheets("Lista Empresas").Range("P3").Calculate

这里有几种情况需要处理。首先,Excel 是否正在运行?如果没有,那就做你已经在做的事情。如果是 - 是否打开了正确的工作簿?如果是 - 将其退回,否则打开它。

Dim ExWbk2 As Workbook
Dim wb As Workbook
Dim exapp As Excel.Application
On Error Resume Next
Set exapp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set exapp = Nothing
End If
On Error GoTo 0
If exapp Is Nothing Then
' Excel is not running
Set exapp = New Excel.Application
Set ExWbk2 = exapp.Workbooks.Open("\XXXListaEmpresas_ajustado.xlsm", UpdateLinks:=0)
ExWbk2.Visible = True
Else
' Excel is running, but is the right book open?
For Each wb In exapp.Workbooks
Debug.Print wb.Name ' <-- This will help you find what to look for
If wb.Name = "ListaEmpresas_ajustado" Then
' Yes, it is!
Set ExWbk2 = wb
End If
Next
If ExWbk2 Is Nothing Then
' No, it wasn't
Set ExWbk2 = exapp.Workbooks.Open("\XXXListaEmpresas_ajustado.xlsm", UpdateLinks:=0)            
End If
End If

找出 Excel 是否正在运行的技巧是GetObject.如果找不到它,它将失败。
for 循环允许根据名称查找正确的工作簿。根据需要进行调整。

如果您知道 Excel 实例中当前处于活动状态的工作表的名称,则以下代码将获取对象。我想这可以使用第一段代码从应用程序标题中获取。

Dim exapp As Excel.Application
Dim ExWbk As Workbook
Dim ExWbk2 As Workbook
Set exapp = GetObject("ListaEmpresas_ajustado.xlsm").Application
exapp.Visible = True
ExWbk2.Sheets("Lista Empresas").Range("P2").Value = ticker
ExWbk2.Sheets("Lista Empresas").Range("P3").Calculate