3

我目前正在使用 Outlook 2010 VBA 宏从电子邮件中提取信息并将其放入 Excel 文件中。这个想法是,每封电子邮件每次都在嵌入在电子邮件消息中的表格中具有相同的字段(名称、订单号、日期等),并且将这些数据放入电子表格中。为此,我目前使用以下代码来获取表格并将其移动到 Excel 中:

'This code is inside a for each loop for each message
Set excelWorksheet2 = excelWorkbook.Worksheets.item(2)
Set excelWorksheet3 = excelWorkbook.Worksheets.item(3)
Set excelWorksheet4 = excelWorkbook.Worksheets.Add(After:=excelWorkbook.Sheets(excelWorkbook.Sheets.count))

Dim mailObj As Outlook.MailItem
Dim doc As Word.Document
Set doc = mailObj.GetInspector.WordEditor

Dim table1, table2, table3 As Object
Set table3 = doc.Tables(4).Range
Set table2 = doc.Tables(3).Range
Set table1 = doc.Tables(2).Range

table1.Copy
excelWorksheet2.Paste
table2.Copy
excelWorksheet4.Paste
table3.Copy
excelWorksheet3.Paste
Set table1 = Nothing
Set table2 = Nothing
Set table3 = Nothing

'I do much more of this to get the data from each table and put it into a master worksheet...
excelWorksheet.Cells(rows, cols + 1).Value = excelWorksheet2.Cells(4, 2).Value 'Contract Number
excelWorksheet.Cells(rows, cols + 2).Value = excelWorksheet2.Cells(4, 4).Value 'Contractor Name 

Set doc = Nothing
Set excelWorksheet2 = Nothing
Set excelWorksheet3 = Nothing
Set excelWorksheet4 = Nothing

我经常收到以下错误,但它不会发生在相同的数据上,它是一种随机的,似乎只发生在 Outlook/电子邮件端:

  • “请求的集合成员不存在。” (错误代码 5941)在该.Range
  • .Copy 行中的“对象'范围'的方法'复制'失败”

如果我单步执行,有时这两个错误都会发生,如果复制失败,宏就会崩溃。

我努力了:

  • 延迟 2 秒
  • 浏览更少的电子邮件(当我选择 > 10 封电子邮件进行处理时,此代码通常会失败)
  • 每封电子邮件后清除剪贴板
  • 通过关闭/释放对象Nothing(不确定这是否是最佳实践,因为我更像是 C/C++/C#/Java 人)

这些似乎都无法远程解决此问题,因为这两个错误都经常弹出,但时断时续。对于调试此问题的下一步将是什么,我真的很茫然,任何帮助将不胜感激!

4

1 回答 1

2

Based on research I have been doing on the issue of the WordEditor tables, it seems as the amount of copy/paste operations and the searching HTML tables just simply do not allow for reliable behavior. One possible solution to this could be to copy the entire email into Excel and parse the tables that way (this still requires copy/paste).

What I did to solve this problem (indirectly) is to save all the emails as HTML files (through Outlook.Application running in Excel: email.SaveAs folderPath + fileName + ".html", olHTML) in a temporary directory and have Excel open the HTML files in a workbook and work with the data that way. This has been much more reliable (added overhead though) and allows for large volumes of emails to be exported to Excel properly.

If anyone wants the exact code to my problem, message me (vindansam at hotmail.com, it's a tad long and has some proprietary information in it).

It's too bad that the WordEditor seems to not handle the information well, maybe Microsoft will beef things up in the next version of Office.

于 2013-07-24T19:47:53.373 回答