且构网

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

如何使用vba读取粘贴在Outlook消息正文中的表?

更新时间:2022-12-03 11:08:28

此示例过程应该会有所帮助.我在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的字段值.变量数据"仅包含与每个字段相对应的值.因此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.