Search code examples
vbaoutlookms-wordemail-attachmentsoffice-automation

Word file gets corrupted when sending via outlook


I have a macro that will populate a word template with fields from an excel sheet and save it as a standalone document [1]. This works fine and is saved successfully on sharepoint, I can open it, download it, edit it everything is fine.

[1]

Sub inpWord()
    Dim bStarted As Boolean, wdApp As Word.Application, wdDoc As Word.Document, wdTemp As String
    
    wdTemp = "XXXXXX SHAREPOINT LINK XXXXXXX"
    Set inpBook = xlApp.Workbooks("Input Tool")
    
    On Error Resume Next 
        'Open word 
       
    Set wdDoc = Documents.Add(Template:=wdTemp, NewTemplate:=False, DocumentType:=wdNewBlankDocument, Visible:=True)
    Filename = "SHAREPOINT FOLDER LINK" & CStr(RefNum) & ".docx?web=1"
    
    With wdDoc
        Set CCDate = .SelectContentControlsByTitle(1)
        'For loop to populate word template
        .SaveAs Filename
    End With

End Sub

I then try sending the document after recalling it from sharepoint using another macro [2], there is no error during the process but the attachment is corrupted every time in the email despite what changes I've tried to make.

[2]

Private Sub CommandButton1_Click()
Dim bStarted As Boolean, oOutlookApp As Outlook.Application, oItem As Outlook.MailItem, xlApp As Object, xlBook As Object

Set xlApp = GetObject(, "Excel.Application")
Set xlBook = xlApp.Workbooks("Purchasing Tracker")

POAttach = "SHAREPOINT LINK" & CStr(PONum) & ".docx?web=1"

On Error Resume Next 'Open Outlook unless already open
    Set oOutlookApp = GetObject(, "Outlook.Application")
    If Err <> 0 Then
        Set oOutlookApp = CreateObject("Outlook.Application")
        bStarted = True
        Err.Clear
    End If
    oOutlookApp.Visible = True

Set oItem = oOutlookApp.CreateItem(olMailItem)

    With oItem
        .To = "RECIEVER"
        .Subject = "XX"
        .HTMLBody = "XX"
        .Attachments.Add Source:=POAttach, Type:=1, _
        DisplayName:="Formula Student Purchase Order: " & CStr(UserForm1.TextBox1.Value)
        .Send
    End With
End Sub

I've tried to only include the necessary portions, any help would be appreciated and happy to provide any more context. All macros are written in the excel documents, nothing is contained in outlook or word.


Solution

  • The Attachments.Add method is not aware about hyperlinks and can't deal with files stored on the remote server. You need to download the file locally and then pass a local file path instead.

    The source of the attachment can be a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment.