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

从Excel VBA中的特定单元格读取数据时出现问题,vba,excel,Vba,Excel,我正试图使用内置的VB宏从文档中发送一封包含Excel工作簿的电子邮件。其中一张表中有数据,与发送电子邮件主题、收件人等相关。我正在尝试使用sheets对象访问这些数据,如下所示 Sub Button1_Click() Dim OutApp As Object Dim OutMail As Object Set OutApp = CreateObject("Outlook.Application") Set OutMail = OutApp.CreateItem

我正试图使用内置的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

我曾尝试使用工作表、工作表、ActiveWorkbook访问单元格,但我确信这只是如何分配数据的问题,因为我不习惯使用VB等语法的语言。非常感谢您的帮助,如果您需要更多信息,请给我留言。

您需要使用“Set”关键字来指定范围

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

这仍然让我经常感到恼火。

我想它也应该是ThisWorkbook,而不是代码中的任何地方。我假设'This'是工作簿变量。但将其替换为ThisWorkbook也可以。@user3964075您最好将ThisWb设置为工作簿,然后设置ThisWb=ThisWorkbook,然后在使用此工作簿的任何地方使用ThisWb。依我拙见
Set subjectCell = ThisWorkbook.Sheets("MailContent").Range("A2")