Este fórum está sendo desativado

Depois de 9 anos, este fórum será desativado. Mas calma.... estamos migrando para uma comunidade no DISCORD. Junte-se a nós.

ENTRAR PARA DISCORD

Tópicos relacionados a códigos VBA, gravação de macros, etc.
#70995
Bom dia,

Criei uma macro para enviar um e-mail, mas queria definir como anexo a enviar o último ficheiro colocado na pasta.

Podem ajudar-me ?

Sub enviar_email()

Set objeto_outlook = CreateObject("Outlook.Application")
Set Email = objeto_outlook.createitem(0)
Email.display
Email.to = ""
Email.cc = ""
Email.bcc = ""

Email.Subject = "Erros de Cálculo" & Format(Now, "ddmmyyyy")

Email.htmlbody = "Bom dia," & "<br><br>Segue em anexo o ficheiro relativo aos erros do processo desta madrugada. <br><br>" _
& "Com os melhores cumprimentos,<br><br> "

Email.Attachments.Add ("D:\Ambiente de Trabalho\Erros\Erros24052022.xlsx")


Email.send

End Sub


Cumprimentos,

Álvaro Gonçalves
#71004
Para descobrir qual arquivo foi salvo por último será preciso fazer um Loop pelos arquivos salvos na pasta de interesse.
O Loop pode ser direcionado para certo tipo de arquivo com base na sua extensão.

Veja se o Sábio Google pode lhe ajudar, pesquise por ~~~> vba DateLastModified
#71141
Bom dia,

Tou a tentar através do código infra, no entanto tenho um erro na linha do dim objtmail.

Consegues ajudar @osvaldomp ?
Código: Selecionar todos
Sub email()
Set objeto_outlook = CreateObject("Outlook.Application")
Set Email = objeto_outlook.CreateItem(0)

Email.display
Email.To = " "
Email.bcc = ""

Email.Subject = "Erros de Cálculo" & Format(Now, "ddmmyyyy")

Email.htmlbody = "Bom dia," & "<br><br>Segue em anexo o ficheiro relativo aos Erros do processo desta madrugada. <br><br>" _
& "Com os melhores cumprimentos,<br><br> "

Dim objShell As Object
Dim objSelectedFolder As Object
Dim objFileSystem As Object
Dim strSourceFolderPath As String
Dim objSourceFolder As Object
Dim objFile As Object
Dim dLastModifiedDate As Date
Dim strLastModifiedFilePath As String
Dim objMail As Outlook.mailItem
    
On Error GoTo ErrorHandler

    'Select a local source folder
    Set objShell = CreateObject("Shell.Application")
    Set objSelectedFolder = objShell.BrowseForFolder(0, "Select the source folder", 0, "")
    strSourceFolderPath = objSelectedFolder.self.Path
    
Set objFileSystem = CreateObject("Scripting.FileSystemObject")
    Set objSourceFolder = objFileSystem.GetFolder(strSourceFolderPath)
 
    If objSourceFolder.Files.Count > 0 Then
       For Each objFile In objSourceFolder.Files
           'Find the last modified file within "xlsx" file type in the selected Windows folder
           If (objFile.DateLastModified > dLastModifiedDate) And (objFileSystem.GetExtensionName(objFile) = "xlsx") Then
              'You can add or change criteria, such as
              'Left(objFile.Name, 4) = "Test" ---> file whose name begins with "Test"
              '(objFile / 1024) / 1024 > 2 --> File exceeds 2 MB
              'Note: Use "And" to connect more than one criteria
              strLastModifiedFilePath = objFile.Path
              dLastModifiedDate = objFile.DateLastModified
           End If
       Next
 
       If strLastModifiedFilePath <> "" Then
          'Confirm attaching it to the current outlook email
          strMsg = "The last modified file in the " & Chr(34) & strSourceFolderPath & Chr(34) & " is: " & vbCrLf & vbCrLf & "File: " & strLastModifiedFilePath & vbCrLf & "Date: " & dLastModifiedDate & vbCrLf & vbCrLf & "Do you want to attach it?"
          nPrompt = MsgBox(strMsg, vbQuestion + vbYesNo, "Confirm Attaching Last Modified File")
 
          If nPrompt = vbYes Then
             Set objMail = Outlook.Application.ActiveInspector.CurrentItem
             objMail.Attachments.Add strLastModifiedFilePath
         End If
      Else
         MsgBox "No file in the selected folder can meet your predefined criteria!", vbExclamation + vbOKOnly
      End If
    Else
      MsgBox "No file exists in the selected Windows folder!", vbExclamation + vbOKOnly
    End If
   
ErrorHandler:
    Exit Sub

MsgBox "E-mail enviado com sucesso", vbInformation


End Sub



#71142
Qual é a mensagem exibida ao ocorrer o erro ?

As declarações de variáveis devem ser colocadas logo abaixo do nome da Sub, e não lá pelo meio do código.

Sub AsnoBozo()
Dim ....
Dim ...
Dim ...
#71144
A referência abaixo precisa ser marcada no editor de VBA.
Microsoft Outlook 16.0 Object Library

No editor clique em Ferramentas | Referências | marque a referência citada.

Dependendo da versão do Excel o trecho 16.0 pode estar como 14.0
Editado pela última vez por osvaldomp em 03 Jun 2022 às 09:43, em um total de 2 vezes.
long long title how many chars? lets see 123 ok more? yes 60

We have created lots of YouTube videos just so you can achieve [...]

Another post test yes yes yes or no, maybe ni? :-/

The best flat phpBB theme around. Period. Fine craftmanship and [...]

Do you need a super MOD? Well here it is. chew on this

All you need is right here. Content tag, SEO, listing, Pizza and spaghetti [...]

Lasagna on me this time ok? I got plenty of cash

this should be fantastic. but what about links,images, bbcodes etc etc? [...]

Estamos migrando para uma comunidade no Discord