如何从特定Excel工作表中选择数据

时间:2014-05-21 14:47:00

标签: excel vba excel-vba outlook

我需要从Excel工作表'sheet1'

上的单元格中选择数据

但是,当我导航到我的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'获取单元格值。

1 个答案:

答案 0 :(得分:1)

您在代码中引用了ActiveSheet,这意味着它将在此行中引用excel中的打开工作表:

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