2014-05-21 33 views
0

我需要選擇一個Excel工作表調用「工作表Sheet1」如何選擇特定的數據的Excel工作表

然而,當我瀏覽到我的Excel文檔不同的表,只是說我跑從細胞數據來自VBA開發者頁面的宏,它從我所在的工作表中獲取數據,而不是'sheet1'。

這裏是我的代碼...

Sub CreateMail() 

    Dim objOutlook As Object 
    Dim objMail As Object 
    Dim rngTo As Range 
    Dim rngBody As Range 

    Set objOutlook = CreateObject("Outlook.Application") 
    Set objMail = objOutlook.CreateItem(0) 

    With ActiveSheet 
     Set rngBody = .Range(.Range("B5"), .Range("D5").End(xlDown)) 
    End With 
    rngBody.Copy 

    With objMail 
     .To = "xxxx" 
     .Subject = "Project Update - " & Range("D2") & " on " & Format(Now(), "dd/mm/yyyy") 
     .display 


    End With 
    SendKeys "^({v})", True 

    On Error GoTo 0 
    Set OutMail = Nothing 
    Set OutApp = Nothing 


End Sub 

任何人都可以解釋爲什麼它會從「工作表Sheet1」當我在這片只取單元格值。

+0

可能重複[Excel宏 - 避免使用Select](http://stackoverflow.com/questions/10714251/excel-macro-avoiding-using-select) – RubberDuck

回答

1

你引用你的代碼,這意味着它會指開片在Excel中在這條線內的ActiveSheet

With ActiveSheet 

您需要引用要通過改變從得到的數據表這:

With Sheets("Sheet1") 

因此,在你的代碼:的

Sub CreateMail() 

    Dim objOutlook As Object 
    Dim objMail As Object 
    Dim rngTo As Range 
    Dim rngBody As Range 

    Set objOutlook = CreateObject("Outlook.Application") 
    Set objMail = objOutlook.CreateItem(0) 

    With Sheets("Sheet1") 
     Set rngBody = .Range(.Range("B5"), .Range("D5").End(xlDown)) 
    End With 
    rngBody.Copy 

    With objMail 
     .To = "xxxx" 
     .Subject = "Project Update - " & Sheets("Sheet1").Range("D2") & " on " & Format(Now(), "dd/mm/yyyy") 
     .display 


    End With 
    SendKeys "^({v})", True 

    On Error GoTo 0 
    Set OutMail = Nothing 
    Set OutApp = Nothing 


End Sub 
相關問題