2015-03-31 59 views
0

我试图使用内置的VB宏从文档内发送包含Excel工作簿的电子邮件。其中一张表中有数据与发送电子邮件(主题,收件人等)相关。我试图访问这些使用Sheets对象,像这样从Excel中的特定单元格读取数据的问题VBA

Sub Button1_Click() 
    Dim OutApp As Object 
    Dim OutMail As Object 

    Set OutApp = CreateObject("Outlook.Application") 
    Set OutMail = OutApp.CreateItem(0) 

    Dim cell As Object 
    Dim count As Integer 

    count = 0 
    For Each cell In Selection 
     count = count + 1 
    Next cell 
    If count <> 1 Then 
     MsgBox ("You must select exactly one cell, which shall be the e-mail address of the recipient") 
     Wscript.Quit 
    Else 
     recipient = ActiveCell.Value 
    End If 

    On Error Resume Next 
    With OutMail 
     .To = recipient 
     .CC = "" 
     .BCC = "" 
     .SentOnBehalfOfName = This.Sheets("MailContent").Range("A2").Value 
     .Subject = This.Sheets("MailContent").Range("A4").Value 
     .Body = This.Sheets("MailContent").Range("A6").Value & vbNewLine & This.Sheets("MailContent").Range("A7") & vbNewLine & vbNewLine & "Næste gang senest den " + This.Sheets("MailContent").Range("A10") & vbNewLine & vbNewLine & This.Sheets("MailContent").Range("A8") 
     .Attachments.Add ActiveWorkbook.Name 
     .Display 
    End With 
    On Error GoTo 0 

    Set OutMail = Nothing 
    Set OutApp = Nothing 
End Sub 

我也能有这个小片断

Sub Button1_Click() 
    Dim subjectCell As Range 
    subjectCell = This.Sheets("MailContent").Range("A2") 
    MsgBox (subjectCell.Value) 
End Sub 

我使用工作表,表试图复制了同样的错误, ActiveWorkbook来访问单元格,但我相信这只是我分配数据的一个问题,因为我不习惯VB等语法的语言。任何帮助非常感谢,如果你需要更多的信息留下评论。

回答

0

您需要使用'Set'关键字来指定范围。

Set subjectCell = ThisWorkbook.Sheets("MailContent").Range("A2") 

这仍然让我感到烦躁不安。

+0

我想在代码中的每个地方它都应该是'ThisWorkbook'而不是'This'。 – BrakNicku 2015-03-31 10:46:24

+0

我假设'这'是一个工作簿变量。交换ThisWorkbook也将工作。 – 2015-03-31 10:50:48

+0

@ user3964075你最好的选择是'Dim ThisWb as Workbook'然后是'Set ThisWb = Thisworkbook',然后在你使用'this'的地方使用'ThisWB'。恕我直言 – FreeMan 2015-03-31 10:55:48

相关问题