How to read table pasted in outlook message body using vba?

删除回忆录丶 提交于 2019-12-19 09:09:54

问题


I need to read table of data as in picure using vba. I used Msg.Body to read the body text but actually i need to find first row as header and rest as data field and update DBMS table accordingly.So is it possible to read the table as I would in excel?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/8061350/how-to-read-table-pasted-in-outlook-message-body-using-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!