从Excel VBA中的特定单元格读取数据时出现问题

时间:2015-03-31 10:37:06

标签: excel vba excel-vba

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

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

我已经尝试使用WorkSheets,Sheets,ActiveWorkbook访问单元格,但我确定这只是我如何分配数据的问题,因为我不习惯使用像VB这样的语法的语言。非常感谢任何帮助,如果您需要更多信息,请给我留言。

1 个答案:

答案 0 :(得分:0)

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

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

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