如何使用 vba 读取粘贴在 Outlook 邮件正文中的表格? [英] How to read table pasted in outlook message body using vba?

查看:78
本文介绍了如何使用 vba 读取粘贴在 Outlook 邮件正文中的表格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 vba 读取图片中的数据表.我使用 Msg.Body 来读取正文,但实际上我需要找到第一行作为标题,其余的作为数据字段并相应地更新 DBMS 表.所以是否可以像我那样读取表擅长?

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?

推荐答案

这个示例程序应该会有所帮助.我在 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.

这篇关于如何使用 vba 读取粘贴在 Outlook 邮件正文中的表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆