2016-08-27 89 views
2

我有根據條件拆分工作簿的代碼。我希望將這些新工作簿中的每一個都發送給不同的人。發送拆分工作簿的每個新工作簿

當我運行宏時,它拆分工作簿並將所有工作表放在我想要的位置。當我嘗試發送時,我只發送1封電子郵件。

Sub savesheetsSend() 

Dim ws As Worksheet 
Dim Filetype As String 
Dim Filenum As Long 
Dim wb As Workbook 
Dim FolderName As String 
Dim open_book As Workbook 
Set outmail = CreateObject("outlook.application") 
Set outmsg = outmail.createitem(0) 

Set wb = Application.ThisWorkbook 

'create directory to save each sheet in 
FolderName = "C:\Users\jpenn\Desktop" & "\" & wb.Name 
MkDir FolderName 

On Error Resume Next 

'save each sheet as workbook in directory 
For Each ws In wb.Worksheets 

    If ws.Range("A1") = 1 Then 
     Filetype = ".xlsm": Filenum = 52 
     ws.Copy 
     xFile = FolderName & "\" & Application.ActiveWorkbook.Sheets(1).Name & Filetype 
     Application.ActiveWorkbook.SaveAs xFile, FileFormat:=Filenum 
    End If 
Next 

'send all new workbooks to email address in CELL("B1") 
For Each open_book In Application.Workbooks 
    If open_book.Name <> ThisWorkbook.Name Then 

     With outmsg 
      .Subject = ActiveWorkbook.Name & " payroll data" 
      .To = ActiveWorkbook.ActiveSheet.Range("b1").Value 
      .body = "I will get to this later" 
      .Attachments.Add Application.ActiveWorkbook.FullName 
      .send 
     End With 
    open_book.Close 
    End If 
Next 

End Sub 
+1

發送的附件,而你是一號每個WS,旁邊保存爲 – 0m3r

+1

移動'設置outmsg = outmail.createitem(0 )''在'循環中outmsg'之前 –

+1

.Attachments.Add(xFile) – 0m3r

回答

0

嘗試這種方式...測試

Option Explicit 
Sub savesheetsSend() 
    Dim Ws As Worksheet 
    Dim Filetype As String 
    Dim xFile As String 
    Dim Filenum As Long 
    Dim Wb As Workbook 
    Dim FolderName As String 
    Dim Open_Book As Workbook 
    Dim OutMsg As Object 
    Dim OutMail As Object 

    Set OutMail = CreateObject("outlook.application") 
    Set Wb = Application.ThisWorkbook 

    'create directory to save each sheet in 
    FolderName = "C:\Users\jpenn\Desktop" & "\" & Wb.Name 
    MkDir FolderName 

    'save each sheet as workbook in directory 
    For Each Ws In Wb.Worksheets 

     If Ws.Range("A1") = 1 Then 
      Filetype = ".xlsm": Filenum = 52 
      Ws.Copy 
      xFile = FolderName & "\" & Application.ActiveWorkbook.Sheets(1).Name & Filetype 
      Application.ActiveWorkbook.SaveAs xFile, FileFormat:=Filenum 

      Set OutMsg = OutMail.createitem(0) 

      With OutMsg 
       .Subject = Ws.Name & " payroll data" 
       .To = ActiveSheet.Range("b1").Value 
       .Body = "I will get to this later" 
       .Attachments.Add (xFile) 
       .Display 
      End With 

      ActiveWorkbook.Close 

     End If 
    Next 
End Sub 
+0

謝謝!,這是比我的清潔,只有一個循環和完美,謝謝你的幫助。 –

相關問題