0

我有以下用于 excel vba 的代码,它将通过电子邮件发送我工作表中的一系列地址。但是,我希望可以使用输入框来确定我想通过电子邮件发送的范围。我遇到的麻烦是让输入成为函数 mailid 理解的值。有什么建议么?

Sub EmailActiveSheetWithOutlook2()

Dim oApp, oMail As Object, _
tWB, cWB As Workbook, _
FileName, FilePath As String

Application.ScreenUpdating = False

'Set email id here, it may be a range in case you have email id on your worksheet

 Sheets("Sheet1").Select
 mailId = Range("b4:b5").Value


'Write your email message body here , add more lines using & vbLf _ at the end of each line

Body = "Hello, it appears you have not yet filled out the transportation contact information excel sheet. This sheet was emailed to you, please complete this and send to me  saved as your firstnamelastname.xls at your earliest convience." & vbLf _
& vbLf _
& "Thanks & Regards" & vbLf _
& vbLf _
& "-Ryan " & vbLf _

'通过outlook发送邮件

Set oApp = CreateObject("Outlook.Application")
Set oMail = oApp.CreateItem(0)
With oMail
    .To = mailid
    .Subject = "Transportation Committee Notice"
    .Body = Body
    '.Attachments.Add tWB.FullName
    .send
End With


End Sub
4

1 回答 1

3

要复制当前代码使用的效果

mailid = Application.InputBox(Prompt:="Select Range", Type:=8)

whereType:=8指定返回类型Range。这会将Value所选范围的属性返回到mailid

或者使用

Dim rng as Range
Set rng = Application.InputBox(Prompt:="Select Range", Type:=8)
mailid = rng.Value

rng然后设置为选定的范围,并且可以在使用前进行验证

请注意,您应该添加错误处理以解决问题,例如用户取消输入框

不要Application.ScreenUpdating = False在发布前设置,InputBox因为这会阻止用户与屏幕交互。

顺便说一句,您的代码使用Dim不正确:Dim'ing 一个没有As子句的变量将其声明为 `Variant.
例如

Dim oApp, oMail As Object

实际上声明oAppVariant, 使用

Dim oApp As Object, oMail As Object
于 2012-08-25T22:33:46.420 回答