excel vba inputbox

我有以下代码为Excel VBA,将通过电子邮件发送我的工作表中的地址范围。 不过,我正在寻找也许使用一个input框来确定我想要发送电子邮件的范围。 我碰到的麻烦是获得input成为函数mailid理解的值。 有什么build议么?

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 

复制当前代码使用的效果

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

其中Type:=8指定Range的返回types。 这将所选范围的Value属性返回给mailid

或者使用

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

然后将rng设置为选定范围,并在使用前进行validation

请注意,您应该添加error handling来解决,例如用户取消InputBox

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

Dim说一句,你的代码错误地使用了Dim :在没有As子句的情况下Dim一个variables声明它为Variant。
例如

 Dim oApp, oMail As Object 

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

 Dim oApp As Object, oMail As Object