【发布时间】:2016-09-08 14:52:08
【问题描述】:
我有一个包含两个工作表的工作簿。工作表“Tickets”是一个列表,其中包括第一列中的经理用户 ID 和其他 3 列中的一些其他数据。工作表“Email_List”包含经理用户 ID、电子邮件地址和名字。
我希望脚本使用用户 ID 在“工单”中选择与“Email_List”中的每个经理相关的行,并将该选择通过电子邮件发送给该经理。
选择部分似乎工作,给相关经理的电子邮件似乎工作,但不仅仅是发送选择;正在发送整个“Tickets”表。
编辑:经过进一步调查,当所有匹配的用户 ID 都位于单个连续行块中时,它可以工作。因此,一种解决方法是在运行此脚本之前对 UserID 列进行排序。
Sub SendSelection()
Dim Sendrng As Range
Dim i As Integer
Dim rCell As Range
Dim rRng As Range
Dim lRow As Long
Dim sht As Worksheet
Dim StartCell As Range
Dim rRng2 As Range
'Set up the range to base the selection on
Set sht = Sheets("Tickets")
Set StartCell = Range("A1")
lRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
Set rRng2 = sht.Range("A1:A" & lRow)
i = 1
'set it to loop through each the user ids
Do While Sheets("Email_List").Cells(i, 1).Value <> ""
'look through cells in first column of data in "Tickets"
For Each rCell In rRng2
'If the userids match, then...
If rCell.Value = Sheets("Email_List").Cells(i, 1).Value Then
'set initial rRng to the first matched cell and the rest of the row
If rRng Is Nothing Then
Set rRng = Range(rCell, rCell.Offset(0, 3))
'then add subsequent matched cells/rows to rRng
Else
Set rRng = Application.Union(rRng, Range(rCell, rCell.Offset(0, 3)))
End If
End If
Next
'select the range of matched data
rRng.Select
'set the selection as the range of data to be sent
Set Sendrng = Selection
'Create the mail and send it
With Sendrng
ActiveWorkbook.EnvelopeVisible = True
With .Parent.MailEnvelope
.Introduction = "TEST ONLY"
With .Item
'get email address from "Email_List"
.To = Sheets("Email_List").Cells(i, 2).Value
.CC = ""
.BCC = ""
.Subject = "**TEST**"
.Send
End With
End With
End With
Set rRng = Nothing
i = i + 1
Loop
End Sub
【问题讨论】:
-
我模拟了几个案例,你的代码运行良好。你有没有要求收件人向你展示他们得到了什么?建议将其修改为
Set StartCell = sht.Range("A1"),但这不会导致您所描述的情况 -
@ShaiRado 是的,我查看了收件人收到的内容。他们都以电子邮件正文中表格的形式获取“票证”工作表上的所有数据。我很难明白为什么这不起作用。当我逐步完成时,我可以看到在发送电子邮件时选择了正确的单元格。就像“Sendrng”被定义为活动工作表,而不仅仅是选定的单元格
-
如果您的 Range 选择只有 1 个单元格(在我的测试中并非如此),那么它将发送整个工作表
-
在我的测试中,没有出现只有 1 个单元格匹配的情况。
-
可能是在“Email_List”工作表中将“Sendrng”设置为单个单元格?即使单步执行不会将该工作表显示为活动工作表。