从Excel发送Outlook电子邮件,将最后一行的范围文本放在主体消息中

我想从我的Excel电子表格发送一封电子邮件到一个包含A列到G列最后一行的范围内的小消息。

我试图添加我的最后一行范围到下面的代码没有成功。

你能帮我吗?

Sub Mail_LastRowRange_Outlook() Dim OutApp As Object Dim OutMail As Object Dim strbody As String Set OutApp = CreateObject("Outlook.Application") Set OutMail = OutApp.CreateItem(0) strbody = "Thanks for your help" & '**I Would like to insert_ my last row range from column A to G in here** On Error Resume Next With OutMail .To = "" .CC = "" .BCC = "" .Subject = "Looking for a solution" .Body = strbody .Attachments.Add ("C:\test.txt") .Send End With On Error GoTo 0 Set OutMail = Nothing Set OutApp = Nothing End Sub 

 Sub test1() Dim lastRow As Long 'get last row from column A of worksheet with 'codename' Sheet1 lastRow = getLastRow(Sheet1, 1) Dim r As Range Set r = Sheet1.Range("A" & lastRow & ":G" & lastRow) Dim str As String 'Join the cell texts with a space - lazy coding... str = Join(Application.Transpose(Application.Transpose(r.Value2)), " ") MsgBox str End Sub Public Function getLastRow(ws As Worksheet, Optional col As Long) As Long Dim arr As Variant If col > 0 Then arr = Intersect(ws.UsedRange, ws.Columns(col)).Value2 Else arr = ws.UsedRange.Value2 End If Dim i As Long, j As Long For i = UBound(arr) To 1 Step -1 For j = UBound(arr, 2) To 1 Step -1 If Len(arr(i, j)) > 0 Then getLastRow = i + ws.UsedRange.Row - 1 Exit Function End If Next j Next i End Function 

上面的函数是在工作表/列中获取实际数据值的最后一行的最健壮的函数。 其他一切都是脆弱的,包括Range.Find("*", , , , , xlPrevious) ,这是易受过滤ListObject的activeCell

下面的函数容易被过滤行,最后一行有数据等。

 Public Function getLastRow2(ws As Worksheet, col As Long) As Long getLastRow2 = ws.Cells(ws.Rows.Count, col).End(xlUp).Row End Function 

确定特定的行,并创build一个范围对象并遍历它,例如:

  Dim rng As range Dim item As range Dim row As Long Set rng = range(Cells(row, 1), Cells(row, 7)) For Each item In rng strBody = strBody & " " & item Next item 

这应该工作,只要A列中的单元格A1到A列中的数据最后一行没有空白单元格。将所有这些“strbody = ….”的行replace。

 Cells(1,1).Select Selection.End(xlDown).Select Dim s As String s = ActiveCell.Value 'A ActiveCell.Offset(0, 1).Select s = s & ActiveCell.Value 'B ActiveCell.Offset(0, 1).Select s = s & ActiveCell.Value 'C ActiveCell.Offset(0, 1).Select s = s & ActiveCell.Value 'D ActiveCell.Offset(0, 1).Select s = s & ActiveCell.Value 'E ActiveCell.Offset(0, 1).Select s = s & ActiveCell.Value 'F ActiveCell.Offset(0, 1).Select s = s & ActiveCell.Value 'G strbody = "Thanks for your help" & s