且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 vba 读取粘贴在 Outlook 邮件正文中的表格?

更新时间:2022-12-03 09:06:29

这个示例程序应该会有所帮助.我在 Excel 中重新创建了您的表格,将其粘贴到 Outlook 电子邮件中并发送给我自己.然后我用这个程序来读取单元格"值.

This sample procedure should help. I recreated your table in Excel, pasted it into an Outlook email and sent it to myself. Then I used this procedure to read the "cell" values.

Sub GetLines()

Dim msg As Outlook.mailItem
Dim rows As Variant
Dim numberofColumns As Long
Dim numberofRows As Long
Dim headerValues As Variant
Dim headerRow() As String
Dim data() As String
Dim i As Long, j As Long

' get currently selected email
Set msg = ActiveExplorer.Selection.item(1)

' tokenize each line of the email
rows = Split(msg.Body, vbCrLf)

' calculate array size
numberofColumns = Len(rows(0)) - Len(Replace(rows(0), Chr(9), ""))
numberofRows = UBound(rows) + 1

' put header row into array
ReDim headerRow(1 To numberofColumns)
headerValues = Split(rows(0), Chr(9))

For i = 1 To numberofColumns
  headerRow(i) = Trim$(headerValues(i - 1))
Next i

' calculate data array size
numberofRows = numberofRows - 1

' put data into array
ReDim data(1 To numberofRows, 1 To numberofColumns)

  For i = 1 To numberofRows
    For j = 1 To numberofColumns
      data(i, j) = Trim$(Split(rows(i), Chr(9))(j - 1))
    Next j
  Next i

End Sub

首先,我们将电子邮件的每一行标记为一个数组.我们计算数组大小,然后创建一个数组来保存表格的第一行(标题").

First we tokenize each line of the email into an array. We calculate the array size, then create an array to hold just the first line of the table (the "header").

然后我们从行数中减去一,因为我们将跳过标题行.然后我们遍历每一行,拆分它并遍历它的值,然后将它们分配给我们的二维数组.

Then we subtract one from the row count because we are going to skip the header row. We then loop through each row, split it and loop through its values, assigning them to our 2D array as we go.

最后,可以迭代变量headerRow"以检索要用于 DBMS 的字段值.变量data"仅包含与每个字段对应的值.所以 headerRow(1) 和 data(n,1) 应该对应于表格第一列中的值.

In the end, the variable "headerRow" can be iterated to retrieve the field values you want to use for your DBMS. The variable "data" contains only the values corresponding to each field. So headerRow(1) and data(n,1) should correspond to the values in the first column of your table.