So I'm trying to make something that takes emails from a specific folder, and saves the attachments in a specific folder. I've taken this code from a previous post and retooled it for my purposes. It runs without error, but it isn't saving the file in the specified folder, and I can't for the life of me figure it out. Can anyone see my errors?
Sub ExtractFirstUnreadEmailDetails()
Dim oOlAp As Object, oOlns As Object, oOlInb As Object
Dim oOlItm As Object, Br As Object
Dim oOlAtch As Object
Dim eSender As String, dtRecvd As String, dtSent As String
Dim sSubj As String, sMsg As String
'~~> Get Outlook instance
Set oOlAp = GetObject(, "Outlook.application")
Set oOlns = oOlAp.GetNamespace("MAPI")
Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox)
Set Br = oOlInb.Folders("Brokers")
'~~> Store the relevant info in the variables
For Each oOlItm In oOlInb.Items.Restrict("[UnRead] = True")
eSender = oOlItm.SenderEmailAddress
dtRecvd = oOlItm.ReceivedTime
dtSent = oOlItm.CreationTime
sSubj = oOlItm.Subject
sMsg = oOlItm.Body
Exit For
Next
Const AttachmentPath As String = "C:\Desktop\Test"
'~~> New File Name for the attachment
Dim NewFileName As String
NewFileName = AttachmentPath & Format(Date, "DD-MM-YYYY") & "-"
'NewFileName = oOlItm.Subject & Format(Date, "DD-MM-YYYY") & "-"
'~~> Extract the attachment from the 1st unread email
For Each oOlItm In Br.Items
For Each oOlAtch In oOlItm.Attachments
Subject = "Test"
NewFileName = Subject
oOlAtch.SaveAsFile NewFileName & oOlAtch.Filename
Next
Exit For
Next
End Sub
I'd be so appreciative if anyone can point anything out. Thanks!
Picking a path at random is the road to failure.
The file should be saved in a folder named Test you created in C:\Desktop
Option Explicit
Sub ExtractFirstUnreadEmailDetails()
' Set up for Outlook
' not for other applications to use Outlook VBA code
Dim oOlInb As Folder
Dim Br As Folder
Dim oOlItm As Object
Dim oOlAtch As attachment
Dim Subject As String
'~~> Get Inbox of Outlook
Set oOlInb = Session.GetDefaultFolder(olFolderInbox)
Set Br = oOlInb.Folders("Brokers")
Const AttachmentPath As String = "C:\Desktop\Test"
'~~> New File Name for the attachment
Dim NewFileName As String
'~~> Extract the attachment from the 1st unread email
For Each oOlItm In Br.Items
For Each oOlAtch In oOlItm.Attachments
Subject = "Test"
' Note the often forgotten path separator
NewFileName = AttachmentPath & "\" & Subject & Format(Date, "DD-MM-YYYY") & "-" & oOlAtch.fileName
' C:\Desktop\Test\Test17-07-2018-fileName
Debug.Print NewFileName
oOlAtch.SaveAsFile NewFileName
Next
Exit For
Next
End Sub
The result should be a file named: Test17-07-2018-Filename in the folder C:\Desktop\Test
Related
After losing files from a HD, data rescue gave me back most of them, but with abstract names (such as file000123.xlsx). I need to rename them using cell values (client name, invoice ref).
I could make a Basic macro that works for this, if I open the files and start the macro myself for each one of those files.
As I have thousands of files to rename, I need that macro to execute on its own, either when documents are loaded, otherwise on a selected folder.
I assigned my macro to the "document loaded" event via the "tools-Customize-Events" menu. Then, I get a "wrong property value" error on the 1st line, the one defining the function.
Is my way of doing wrong ? Do I have to modify the macro for it to work there ?
Context :
This macro is in "My macros", not within the documents.
using libreOffice 7 on Linux
working on .xlsx files
Thanks for any help, my libreOffice Basic is even poorer than my English.. B-)
My code :
function getFullRep(sPath As String) As String
Dim cpt As Integer
Dim buf As String
Const SLASH = "/"
buf = ""
for cpt = Len(sPath) to 1 step -1
if Mid(sPath, cpt, 1) = SLASH then
buf = Left(sPath, cpt)
exit for
end if
next
getFullRep = buf
end function
Sub Main
Dim oDoc as Object
Dim sG2 as String
Dim sO2 as String
Dim sO as String
Dim sPathBackupFolder as String
Dim filespec As string
Dim laDate As String
Dim myfilename As String
Dim oFeuille As Object
Dim sNomFeuille As String
oDoc = ThisComponent
sPathBackupFolder = getFullRep (oDoc.location)
oFeuille = oDoc.getCurrentController().getActiveSheet()
sNomFeuille = oFeuille.getName()
laDate = Format(Now(),"YYMMDDhhmmss")
If oFeuille.GetCellRangeByName("G14").String <>"" Then
sG2 = oFeuille.GetCellRangeByName("G14").String
sO2 = oFeuille.GetCellRangeByName("A15").String
else
sG2 = oFeuille.GetCellRangeByName("G15").String
sO2 = oFeuille.GetCellRangeByName("A16").String
End If
sO = Replace(sO2, "Facture N°", "")
'Chemin et nom de fichier composé
myfilename = sPathBackupFolder+sG2+" - "+sO+" - "+laDate+".ods"
'Enregistrer sous
dim document as object
dim dispatcher as object
' ----------------------------------------------------------------------
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
' ----------------------------------------------------------------------
dim args1(1) as new com.sun.star.beans.PropertyValue
args1(0).Name = "URL"
args1(0).Value = ConvertToUrl(myfilename) 'On converti le chemin
args1(1).Name = "FilterName"
args1(1).Value = "calc8"
dispatcher.executeDispatch(document, ".uno:SaveAs", "", 0, args1())
oDoc.store
oDoc.close(True)
End Sub
You are getting the error because the document has not completely opened yet. Instead, attach to the event "View Created", and make sure to save to "LibreOffice" (as opposed to individual document).
By the way, it would be a good idea to give your sub a more appropriate name than "Main".
Hope that helps!
This code is in MS Access (2010) VBA, using the Redemption library with Microsoft Outlook 2010.
I had this process working before, but we recently had a Citrix upgrade that I guess reset something in my Outlook and now the process no longer works.
I have a folder of .msg files which are basically pre-made email templates with all the proper formatting, images, text, etc.
This is what I was doing before:
Dim outlookApp As Object, namespace As Object
Dim oItem, MyItem
Set outlookApp = CreateObject("Outlook.Application")
Set namespace = outlookApp.GetNamespace("MAPI")
namespace.Logon
Set MyItem = outlookApp.CreateItemFromTemplate(path_to_dot_msg_file)
'And then there are many calls like this:
MyItem.HTMLBody = Replace(MyItem.HTMLBody, "Dear Person,", "Dear " & name)
'...
Set safeItem = CreateObject("Redemption.SafeMailItem")
Set oItem = MyItem
safeItem.Item = oItem
'this next line displays the email, and as of this line, it looks correct
'safeItem.Display
'but as of this line, the issue occurs
safeItem.HTMLBody = "<p>This is an extra message that shows up before the .msg file</p>" & safeItem.HTMLBody
safeItem.Recipients.ResolveAll
safeItem.Send
Now when the email is sent, the .msg contents aren't present at all -- the only thing that shows up is the "extra message" that I prepended to the HTMLBody.
What do I need to change or update? Is this something I need to change in the code, or in my Outlook settings, etc?
Extra: body insertion:
Function insertStringBodyTag(htmlBody As String, stringToInsert As String)
Dim s As String
Dim i As Integer
s = htmlBody
i = InStr(1, s, "<body")
i = InStr(i, s, ">")
s = Left(s, i) & stringToInsert & Right(s, Len(s) - i)
insertStringBodyTag = s
End Function
'Called with safeItem.htmlBody = insertStringBodyTag(safeItem.htmlBody, prefix_string)
You cannot concatenate 2 HTML strings and expect a valid HTML string back - the two must be merged - find the position of the "<body"substring in the original HTML body, then find the positon of the following ">" (this way you take care of the body element with attributes), then insert your HTML string following that ">".
I have a main form with a 'help' button which opens a simple form with a textbox that a user can use to submit issues noted with the main form. I would like the contents of what the user types into the textbox to be emailed to myself and a co-worker using a 'send' button.
I found the following code on stackoverflow which works except I can't figure out how to have the body of the email include what the user types into the textbox instead of the static text that's currently in the code.
Here's how the code looks now:
Private Sub SendEmail_Click()
Dim olApp As Object
Dim objMail As Object
Dim Issue As String
strIssue = Me.ContactMessageBox
On Error Resume Next 'Keep going if there is an error
Set olApp = GetObject(, "Outlook.Application") 'See if Outlook is open
If Err Then 'Outlook is not open
Set olApp = CreateObject("Outlook.Application") 'Create a new instance
End If
'Create e-mail item
Set objMail = olApp.CreateItem(olMailItem)
With objMail
.To = "emailaddress.com"
.Subject = "Form issue"
.Body = "strIssue"
.send
End With
MsgBox "Operation completed successfully"
End Sub
Does anyone have ideas about how to do this?
Change
Dim Issue As String
strIssue = Me.ContactMessageBox
...
.Body = "strIssue"
to
Dim strIssue As String
strIssue = Me.ContactMessageBox
...
.Body = strIssue
If you put your variable between "" then it is read as a string instead of the variable.
im trying to send an email from a VBScript, it will eventually be added into a currently working script as an else if (if this is possible).
im getting an error at line 23 character 32?
Dim outobj, mailobj
Dim strFileText
Dim objFileToRead
Set outobj = CreateObject("Outlook.Application")
Set mailobj = outobj.CreateItem(0)
strFileText = GetText("C:\test\test 2.txt")
With mailobj
.To = "user#user.com"
.Subject = "Testmail"
.Body = strFileText
.Display
End With
Set outobj = Nothing
Set mailobj = Nothing
End Sub
Function GetText(sFile as String) As String
Dim nSourceFile As Integer, sText As String
nSourceFile = FreeFile
Open sFile For Input As #nSourceFile
sText = Input$(LOF(1), 1)
Close
GetText = sText
End Function
what do i need to add to get line 23 to work and the script to finally do what i need it to, i have copied most of this script from elsewhere due to a sincere lack of VBscripting knowledge?
Take a look at the Using Automation to Send a Microsoft Outlook Message article. It provides a sample code and describes all the required steps for sending emails.
Try this: remove the GetText function entirely, and replace the line
strFileText = GetText("C:\test\test 2.txt")
with
Set fso = CreateObject("Scripting.FileSystemObject")
strFileText = fso.OpenTextFile("C:\test\test 2.txt").ReadAll
I am have the following code for excel vba that will email a range of addresses in my sheet. Howeve, I am looking to maybe use an inputbox to determine what the range is that I would like to email. The trouble i run into is getting the input to become a value that the function mailid understands. any suggestions?
Sub EmailActiveSheetWithOutlook2()
Dim oApp, oMail As Object, _
tWB, cWB As Workbook, _
FileName, FilePath As String
Application.ScreenUpdating = False
'Set email id here, it may be a range in case you have email id on your worksheet
Sheets("Sheet1").Select
mailId = Range("b4:b5").Value
'Write your email message body here , add more lines using & vbLf _ at the end of each line
Body = "Hello, it appears you have not yet filled out the transportation contact information excel sheet. This sheet was emailed to you, please complete this and send to me saved as your firstnamelastname.xls at your earliest convience." & vbLf _
& vbLf _
& "Thanks & Regards" & vbLf _
& vbLf _
& "-Ryan " & vbLf _
'Sending email through outlook
Set oApp = CreateObject("Outlook.Application")
Set oMail = oApp.CreateItem(0)
With oMail
.To = mailid
.Subject = "Transportation Committee Notice"
.Body = Body
'.Attachments.Add tWB.FullName
.send
End With
End Sub
To replicate the effect of your current code use
mailid = Application.InputBox(Prompt:="Select Range", Type:=8)
where Type:=8 specifies a return type of Range. This returns the Value property of the selected range into mailid
Alternatively use
Dim rng as Range
Set rng = Application.InputBox(Prompt:="Select Range", Type:=8)
mailid = rng.Value
rng is then set to the selected range, and can be validated before use
Note that you should add error handling to account for, eg user Cancelling the InputBox
Do not set Application.ScreenUpdating = False before issuing InputBox as this will prevent the user interacting with the screen.
As an aside, your code uses Dim incorrectly: Dim'ing a variable without a As clause declares it as `Variant.
eg
Dim oApp, oMail As Object
actually declares oApp as a Variant, use
Dim oApp As Object, oMail As Object