excel vba输入框

时间:2012-08-25 19:13:58

标签: excel email excel-vba vba

我有以下代码用于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 _

'通过展望

发送电子邮件
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

1 个答案:

答案 0 :(得分:2)

要复制当前代码的效果

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

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

或者使用

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

rng设置为所选范围,并可在使用前验证

请注意,您应该为帐户添加错误处理,例如用户取消InputBox

请勿在发出Application.ScreenUpdating = False之前设置InputBox,因为这会阻止用户与屏幕进行互动。

顺便说一下,您的代码错误地使用了DimDim没有As子句的变量将其声明为`变体。
例如

Dim oApp, oMail As Object

实际上将oApp声明为Variant,使用

Dim oApp As Object, oMail As Object