Outlook Error: user-defined type not defined referring to Excel workbook

Outlook Error: user-defined type not defined referring to Excel workbook

我每天收到 50 封 Excel sheet 的邮件。我想将每个 Excel sheet 的第一行添加到我计算机上现有的 Excel sheet。

我首先编写了一个脚本,将这些 sheet 合并到本地(我下载了 Excel sheet 然后 运行 我的脚本),这里一切正常。

现在我尝试将脚本直接放入 Outlook,因此每当收到其中一封电子邮件时都会自动完成。

本来我想添加一个规则,宏应该是运行的基础,但这不起作用。我找到的解决方案是在“ThisOutlookSession”中的子例程中调用宏:

这是我第一次为 outlook 编写宏,所以我不确定我是否正确传递了参数。

当调用我的 Modul2 时,我立即得到错误

user-defined type not defined

在线 Dim wb_master As WorkbookDim wb_email As Workbook

下面是一个小型代码示例(这里只是将文件名添加到 ID 列中):

Sub Merge_oewaReport(itm As Outlook.MailItem)
Dim wb_path As String
Dim wb_master As Workbook
Dim ws_master As String

Dim objAtt As Outlook.Attachment
Dim FileName As String
Dim wb_email As Workbook
Dim j As Integer
Dim ir_last As Integer

wb_path = "\swi56prof01\UserData$\heinreca\Documents\Outlook-Dateien\AllData.xlsx"
Set wb_master = Workbooks.Open(wb_path)
ir_last = wb_master.Worksheets(ws_master).Range("A" & Rows.Count).End(xlUp).Row

For Each objAtt In itm.Attachments
    FileName = objAtt.DisplayName
    Set wb_email = Workbooks.Open(FileName, True, True)
    fID = Split(FileName, " - ")
    j = wb_master.Worksheets(ws_master).Cells.Find(What:="ID", SearchDirection:=xlNext, SearchOrder:=xlByColumns).Column
    wb_master.Worksheets(ws_master).Cells(ir_last + 1, j) = fID(0)
Next

我检查了工具>参考解决方案。 Microsoft Office 16.0 对象库中的勾号已经存在。

我尝试定义新工作簿而不仅仅是工作簿。


编辑: 我决定尝试后期绑定方法并更改了一些 Dims:

Dim app_master As Object
Dim wb_master As Object
Dim ws_master As Object
Dim ic_last As Integer

其次是:

Set app_master = CreateObject("Excel.Application")
Set wb_master = app_master.Workbooks.Open(wb_path)
Set ws_master = wb_master.Sheets(1)

但是现在 returns 一个错误

Variable not defined

行:

ic_last = ws_master.Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByColumns).Column

突出显示“xlPrevious”。

When my module2 is called, I immediatly get the "user-defined type not defined" error, on the line Dim wb_master As Workbook, and on Dim wb_email As Workbook.

有两种可能的解决方法:

  1. 添加一个 Excel COM 引用,这样声明的类型将对 VBA 可用。这叫做early-binding.

  2. 如果您不想添加 Excel COM 引用,请将对象声明为对象。这叫做late-binding.

Using early binding and late binding in Automation and Early Binding vs. Late Binding: The Essential Guide for VBA Developers 文章中阅读更多相关信息。