在VBA中将单元格的值写入另一个Excel

时间:2018-04-25 06:27:23

标签: excel vba excel-vba outlook

我有这段代码通过Outlook发送电子邮件:

Sub AutoEmail()
    On Error GoTo Cancel

    Dim Resp As Integer
    Resp = MsgBox(prompt:=vbCr & "Yes = Review Email" & vbCr & "No = Immediately Send" & vbCr & "Cancel = Cancel" & vbCr, _
    Title:="Review email before sending?", _
    Buttons:=3 + 32)

    Select Case Resp

        'Yes was clicked, user wants to review email first
        Case Is = 6
            Dim myOutlook As Object
            Dim myMailItem As Object

            Set otlApp = CreateObject("Outlook.Application")
            Set otlNewMail = otlApp.CreateItem(olMailItem)
            FName = Application.ActiveWorkbook.FullName

            With otlNewMail
            .To = Cells(33, 10)
            .CC = Cells(1, 1)
            .Subject = Cells(23, 10) & ": " & Cells(21, 10)
            .Body = "Good morning" & vbCr & vbCr & "" & Cells(23, 10) & "."
            .Attachments.Add FName
            .Display

            End With


            Set otlNewMail = Nothing
            Set otlApp = Nothing
            Set otlAttach = Nothing
            Set otlMess = Nothing
            Set otlNSpace = Nothing


        'If no is clicked
        Case Is = 7
            Dim myOutlok As Object
            Dim myMailItm As Object

            Set otlApp = CreateObject("Outlook.Application")
            Set otlNewMail = otlApp.CreateItem(olMailItem)
            FName = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name

            With otlNewMail
            .To = ""
            .CC = ""
            .Subject = ""
            .Body = "Good Morning," & vbCr & vbCr & " " & Format(Date, "MM/DD") & "."
            .Attachments.Add FName
            .Send
            '.Display
            'Application.Wait (Now + TimeValue("0:00:01"))
            'Application.SendKeys "%s"

            End With

            'otlApp.Quit

            Set otlNewMail = Nothing
            Set otlApp = Nothing
            Set otlAttach = Nothing
            Set otlMess = Nothing
            Set otlNSpace = Nothing
        'If Cancel is clicked
        Case Is = 2
Cancel:
            MsgBox prompt:="No Email has been sent.", _
            Title:="EMAIL CANCELLED", _
            Buttons:=64

    End Select

End Sub

然而,我还想补充一点。我想通过Outlook发送电子邮件后将一些单元格写入另一个excel,让我们说A2到B15。我要写的excel文件位于C:\ Users \ Computername \ Desktop \ Savingdata.xlsx

1 个答案:

答案 0 :(得分:0)

莫特,

尝试以下操作,在代码的开头添加以下两行:

Dim wbThisWorkbook, wbTheOneToSaveTo As Workbook
Set wbThisWorkbook = Workbooks("TheNameOfYourCurrentWorkbook")

然后在发送例行程序后,添加:

Set wbTheOneToSaveTo = Workbooks.Open ("C:\Users\Computername\Desktop\Savingdata.xlsx")
wbThisWorkbook.Sheets("TheNameOfThe Worksheet").Range("A2").Copy
wbTheOneToSaveTo.Sheets("TheNameOfTheWorksheet").Range("B15").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False  'adjust parameters according to your needs
wbTheOneToSaveTo.Close True
wbThisWorkbook.Activate

希望这有帮助!