2015-03-31 63 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

相關問題