Merging two Excel VBA Code (Save as PDF + Send Via Outlook) - excel

kindly I have a two VBA codes one is to save the printed area as PDF with the same name as the workbook is and save file location is Desktop and it works fine
and I do have another code which start outlook new message and take some specific cell value as subject and another value as body.
The problem is I want the code of the new mail to attach that saved PDF file from code 1 and make the subject to be same as PDF file name.
The save pdf code is:
Sub Save_as_pdf()
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = "C:\Users\" & Environ("UserName") & "\Desktop\" & ThisWorkbook.Name
If FSO.FileExists(ThisWorkbook.FullName) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=sNewFilePath, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
End Sub
... and the second outlook new email code is :
Private Declare Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
Sub SendEMail()
Dim Email As String, Subj As String
Dim Msg As String, URL As String
Email = " "
Subj = "P.O # " & "-" & Cells(9, 5) & "-" & Cells(15, 2) & "-" & Cells(15, 8) & Cells(15, 7)
Msg = " "
Msg = "Dear Mr. " & vbCrLf & vbCrLf & "Good Day" & vbCrLf & vbCrLf & "Kindly find the attahched P.O to be delivered to " & Cells(10, 12)
'Replace spaces with %20 (hex)
Subj = Application.WorksheetFunction.Substitute(Subj, " ", "%20")
Msg = Application.WorksheetFunction.Substitute(Msg, " ", "%20")
'Replace carriage returns with %0D%0A (hex)
Msg = Application.WorksheetFunction.Substitute(Msg, vbCrLf, "%0D%0A")
'Create the URL
URL = "mailto:" & Email & "?subject=" & Subj & "&body=" & Msg
'Execute the URL (start the email client)
ShellExecute 0&, vbNullString, URL, vbNullString, vbNullString, vbNormalFocus
'Wait two seconds before sending keystrokes
'Application.Wait (Now + TimeValue("0:00:02"))
'Application.SendKeys "%s"
End Sub
I hope I could clarify my problem fine.
Thanks in advance.

You can try this :
It changes the PDF export to a function to get the file path and use it as an argument in the other one.
URL method doesn't works with attachments, so below is some code for Outlook(edited to contain the whole code)
Preparing mail with Outlook (sorry for french comments):
Sub Send_To_Pdf()
Dim PdfPath As String
Dim BoDy As String
BoDy = Msg = "Dear Mr. " & vbCrLf & vbCrLf & "Good Day" & vbCrLf & vbCrLf & "Kindly find the attahched P.O to be delivered to " & Cells(10, 12)
PdfPath = Save_as_pdf
EnvoiMail Right(PdfPath, InStr(1, StrReverse(PdfPath), "\") - 1), "recepient1#domain.com;recepient2#domain.com", , , BoDy, 1, PdfPath
End Sub
Public Function Save_as_pdf() As String
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = "C:\Users\" & Environ("UserName") & "\Desktop\" & ThisWorkbook.Name
If FSO.FileExists(ThisWorkbook.FullName) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=sNewFilePath, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
Save_as_pdf = sNewFilePath
End Function
Sub EnvoiMail(Subject As String, Destina As String, Optional CCdest As String, Optional CCIdest As String, Optional BoDyTxt As String, Optional NbPJ As Integer, Optional PjPaths As String)
Dim MonOutlook As Object
Dim MonMessage As Object
Set MonOutlook = CreateObject("Outlook.Application")
Set MonMessage = MonOutlook.createitem(0)
Dim PJ() As String
PJ() = Split(PjPaths, ";")
With MonMessage
.Subject = Subject '"Je suis content"
.To = Destina '"marcel#machin.com;julien#chose.com"
.cc = CCdest '"chef#machin.com;directeur#chose.com"
.bcc = CCIdest '"un.copain#supermail.com;une-amie#hotmail.com"
.BoDy = BoDyTxt
If PjPaths <> "" And NbPJ <> 0 Then
For i = 0 To NbPJ - 1
'MsgBox PJ(I)
.Attachments.Add PJ(i) '"C:\Mes Documents\Zoulie Image.gif"
Next i
End If
.display
'.send '.Attachments.Add ActiveWorkbook.FullName
End With '?plusieurs?MonMessage.Attachments.Add "D:\Prof\Janvier\Base clients.mdb"
Set MonOutlook = Nothing
End Sub

Related

How can I password protect the zip folder in VBA?

I want to password protect the zip folder not the files in zip folder using VBA.
for example: if there is folder test.zip and there is file test.xlsx in it. I want to have a password on folder test.zip. Can someone help? Will be highly appreciated. Thanks
This procedure accepts an argument named NewFolder, which represents the folder to which the user is trying to switch. If this folder’s name is Confidential, the procedure asks the user to enter the password. If the password doesn’t match, the Cancel argument is set to True, which means the folder isn’t displayed.
Hope this will help you:
Sub zip_activeworkbook()
Dim strDate As String, DefPath As String
Dim FileNameZip, FileNameXls
Dim oApp As Object
If ActiveWorkbook Is Nothing Then Exit Sub
DefPath = ActiveWorkbook.Path
If Len(DefPath) = 0 Then
msgbox "Please Save activeworkbook before zipping" & Space(12), vbInformation, "zipping"
Exit Sub
End If
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
'Create date/time string and the temporary xls and zip file name
strDate = Format(Now, " dd-mmm-yy h-mm-ss")
FileNameZip = DefPath & Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4) & strDate & ".zip"
FileNameXls = DefPath & Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4) & strDate & ".xls"
If Dir(FileNameZip) = "" And Dir(FileNameXls) = "" Then
'Make copy of the activeworkbook
ActiveWorkbook.SaveCopyAs FileNameXls
'Create empty Zip File
newzip (FileNameZip)
'Copy the file in the compressed folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameZip).CopyHere FileNameXls
'Keep script waiting until Compressing is done
On Error Resume Next
Do Until oApp.Namespace(FileNameZip).items.Count = 1
Application.Wait (Now + TimeValue("0:00:01"))
Loop
On Error GoTo 0
'Delete the temporary xls file
Kill FileNameXls
msgbox "completed zipped : " & vbNewLine & FileNameZip, vbInformation, "zipping"
Else
msgbox "FileNameZip or/and FileNameXls exist", vbInformation, "zipping"
End If
End Sub
Private Sub newzip(sPath)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
If Len(Dir(sPath)) > 0 Then Kill sPath
Open sPath For Output As #1
Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
Close #1
End Sub
You may find my version easier to use and understand. Here is the macro code along with an example of using it. The password is optional.
Private Declare Function ShellExecute _
Lib "Shell32.dll" Alias "ShellExecuteA" _
(ByVal hWnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) _
As Long
Sub ZipFile(FileName As String, Optional ByVal Password As String)
Dim CmdLine As String
Dim Ext As Long
Dim FilePath As String
Dim RetVal As Long
Dim Path As Long
Dim ZipName As String
' If no path is specified use the current directory
Path = InStrRev(FileName, "\")
FilePath = IIf(Path = 0, CurDir & "\", "")
' Check if file exists
If Dir(FilePath & FileName) = "" Then
MsgBox "File Not Found" & vbCrLf & " " & FilePath & FileName
Exit Sub
End If
' Name for the zip archive
Ext = InStrRev(FileName, ".")
ZipName = FilePath & IIf(Ext = 0, FileName & ".zip", Left(FileName, Ext) & "zip")
' Command line string - file names must include quotes
If Password = "" Then
CmdLine = "-min -a -en " & Chr$(34) & ZipName & Chr$(34) & " " _
& Chr$(34) & FileName & Chr$(34)
Else
CmdLine = "-min -a -en -s" & Chr$(34) & Password & Chr$(34) _
& " " & Chr$(34) & ZipName & Chr$(34) & " " _
& Chr$(34) & FileName & Chr$(34)
End If
' Command line String to Unzip a file
'CmdLine = "-min -e " & Chr$(34) & ZipFileName & Chr$(34) & " " _
' & FolderPath
' Zip the file and save it in the archive
RetVal = ShellExecute(0&, "", "WinZip32.exe", CmdLine, FilePath, 1&)
' Check for Errors are from 0 to 32
If RetVal <= 32 Then
Select Case RetVal
Case 2 'SE_ERR_FNF
Msg = "File not found"
Case 3 'SE_ERR_PNF
Msg = "Path not found"
Case 5 'SE_ERR_ACCESSDENIED
Msg = "Access denied"
Case 8 'SE_ERR_OOM
Msg = "Out of memory"
Case 32 'SE_ERR_DLLNOTFOUND
Msg = "DLL not found"
Case 26 'SE_ERR_SHARE
Msg = "A sharing violation occurred"
Case 27 'SE_ERR_ASSOCINCOMPLETE
Msg = "Incomplete or invalid file association"
Case 28 'SE_ERR_DDETIMEOUT
Msg = "DDE Time out"
Case 29 'SE_ERR_DDEFAIL
Msg = "DDE transaction failed"
Case 30 'SE_ERR_DDEBUSY
Msg = "DDE busy"
Case 31 'SE_ERR_NOASSOC
Msg = "Default Email not configured"
Case 11 'ERROR_BAD_FORMAT
Msg = "Invalid EXE file or error in EXE image"
Case Else
Msg = "Unknown error"
End Select
Msg = "File Not Zipped - " & Msg & vbCrLf & "Error " & RetVal
MsgBox Msg, vbExclamation + vbOKOnly
End If
Example of using the macro:
Sub ZipTest()
ZipFile "C:\PF Credits.xls", Password:="123"
End Sub

Cell text truncated to about 1390 characters

I modified the code here - https://www.extendoffice.com/documents/excel/3560-excel-send-personalized-email.html
If the text in the cell is long, it is truncated.
I tried increasing the application time value to 0.20, but that did nothing. It got truncated at the same point.
#If VBA7 And Win64 Then
Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hwnd As LongPtr, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As LongPtr
#Else
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hwnd As Long, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
#End If
Sub SendEMail()
Dim xEmail As String
Dim xSubj As String
Dim xMsg As String
Dim xURL As String
Dim i As Integer
Dim k As Double
Dim xCell As Range
Dim xRg As Range
Dim xTxt As String
On Error Resume Next
xTxt = ActiveWindow.RangeSelection.Address
Set xRg = Application.InputBox("Please select the data range:", "navneesi", xTxt, , , , , 8)
If xRg Is Nothing Then Exit Sub
For i = 1 To xRg.Rows.Count
' Get the email address
xEmail = xRg.Cells(i, 1)
' Message subject
xSubj = "Validation Assignment"
' Compose the message
xMsg = ""
xMsg = xMsg & "Validation Assignment: " & vbCrLf & vbCrLf
xMsg = xMsg & " Order ID: " & xRg.Cells(i, 2).Text & vbCrLf
xMsg = xMsg & " Marketplace ID: " & xRg.Cells(i, 3).Text & vbCrLf
xMsg = xMsg & " Order Day: " & xRg.Cells(i, 4).Text & vbCrLf
xMsg = xMsg & " Seller ID: " & xRg.Cells(i, 5).Text & vbCrLf
xMsg = xMsg & " Product Code: " & xRg.Cells(i, 6).Text & vbCrLf
xMsg = xMsg & " Item Name: " & xRg.Cells(i, 7).Text & vbCrLf
xMsg = xMsg & " Defect Source: " & xRg.Cells(i, 8).Text & vbCrLf
xMsg = xMsg & " Defect Day: " & xRg.Cells(i, 9).Text & vbCrLf
xMsg = xMsg & " Defect Text: " & xRg.Cells(i, 10).Text & vbCrLf
' Replace spaces with %20 (hex)
xSubj = Application.WorksheetFunction.Substitute(xSubj, " ", "%20")
xMsg = Application.WorksheetFunction.Substitute(xMsg, " ", "%20")
' Replace carriage returns with %0D%0A (hex)
xMsg = Application.WorksheetFunction.Substitute(xMsg, vbCrLf, "%0D%0A")
' Create the URL
xURL = "mailto:" & xEmail & "?subject=" & xSubj & "&body=" & xMsg
' Execute the URL (start the email client)
ShellExecute 0&, vbNullString, xURL, vbNullString, vbNullString, vbNormalFocus
' Wait two seconds before sending keystrokes
Application.Wait (Now + TimeValue("0:00:02"))
Application.SendKeys "%s"
Next
End Sub
Well, 1390 doesn't seem like any kind of restriction that I have ever heard about. Maybe 255 characters, or a variable-length string of up to approximately 2 billion (2^31) characters, etc. Can you try doing it this way?
Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("Sheet1")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)
'Enter the path/file names in the C:Z column in each row
Set rng = sh.Cells(cell.Row, 1).Range("C1:Z1")
If cell.Value Like "?*#?*.?*" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = cell.Value
.Subject = "Testfile"
.Body = "Hi " & cell.Offset(0, -1).Value
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
End If
End If
Next FileCell
.Send 'Or use .Display
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
NOTE:
Make a list in Sheets("Sheet1") with :
In column A : Names of the people
In column B : E-mail addresses
In column C:Z : Filenames like this C:\Data\Book2.xls (don't have to be Excel files)
The Macro will loop through each row in "Sheet1" and if there is a E-mail address in column B
and file name(s) in column C:Z it will create a mail with this information and send it.
Most relevant URL:
https://www.rondebruin.nl/win/s1/outlook/amail6.htm
Parent URL:
https://www.rondebruin.nl/win/s1/outlook/mail.htm
Found a fix. Instead of usingCells(i, 5).Text use Cells(i, 5).Value.
This makes sure the cell content is sent to outlook as it is instead of converting it to text first which gives rise to issues. (The code in the question was also unable to render chinese text.)
Also, instead of executing a mail to url, I included the object library for outlook and declared the object for outlook application and for mail item. Dim olApp As Outlook.Application
Dim olMail As Outlook.MailItem

Set Focus Back to Excel, Mac VBA 2016

I am currently using the following VBA code in Excel for MAC 2016:
Sub MailWorkSheet()
Dim SourceWb As Workbook, DestWb As Workbook, sh As Worksheet
Dim strbody As String, TempFileName As String
If Val(Application.Version) < 15 Then Exit Sub
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
'Check if the Script File is in the correct location
If CheckScript(ScriptFileName:="ExcelOutlook.scpt") = False Then
MsgBox "Sorry the ExcelOutlook.scpt file is not in the correct
location, " & _
"Email File Manually."
Exit Sub
End If
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
'Set reference to the source workbook
Set SourceWb = ActiveWorkbook
'Create the body text in the strbody string
strbody = "<FONT size=""3"" face=""Calibri"">"
strbody = strbody & "Hello:" & "<br>" & "<br>" & _
"XXXXXXX." & "<br>" & _
" " & "<br>" & _
"XXXXXXX." & "<br>" & _
" " & "<br>" & _
"XXXXXXX!!"
strbody = strbody & "</FONT>"
'Copy the ActiveSheet to a new workbook
ActiveSheet.Copy
Set DestWb = ActiveWorkbook
'Delete the button on the one sheet workbook
On Error Resume Next
DestWb.Sheets(1).DrawingObjects.Visible = True
DestWb.Sheets(1).DrawingObjects.Delete
On Error GoTo 0
'Enter the name of the file just created
TempFileName = "Long Lane Merit Sheet" & " " _
& Range("A2") & " " & Format(Now, "mmm-dd-yy")
'Call the MailWithMac function to save the new file and create the
mail
MailWithMac _
subject:="XXXXXXX", _
mailbody:=strbody, _
toaddress:=Range("A3"), _
ccaddress:="", _
bccaddress:="", _
displaymail:=True, _
accounttype:="", _
accountname:="", _
attachment:=TempFileName, _
FileFormat:=SourceWb.FileFormat
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
'Turn on Automatic Calculation
Application.Calculation = xlCalculationAutomatic
'Turn Alert Messages On
Application.DisplayAlerts = True
End Sub
It works great to email the current sheet through Outlook.
The problem I am having is that I want the focus to return to the Excel sheet. What is happening now is that the Outlook screen along with a new email pops up. After hitting send, the new email screen goes away, but the main Outlook window remains.
How do I set focus back to Excel?
I have found that the solution is to use Applescript to achieve the desired effect. Here is the whole script:
ption Explicit
Sub MailWorkSheet()
'Only working in Excel 2016 for the Mac with Outlook 2016
Dim SourceWb As Workbook, DestWb As Workbook, sh As Worksheet
Dim strbody As String, TempFileName As String
Dim RunMyScript As String
'Exit the sub if it is Mac Excel 2011 or lower
If Val(Application.Version) < 15 Then Exit Sub
'Turn off Automatic Calculation
Application.Calculation = xlCalculationManual
'Turn off Alerts
Application.DisplayAlerts = False
'Check if the Script File is in the correct location
If CheckScript(ScriptFileName:="ExcelOutlook.scpt") = False Then
MsgBox "Sorry the ExcelOutlook.scpt file is not in the correct location, " & _
"Email File Manually."
Exit Sub
End If
With Application
'.ScreenUpdating = False
.EnableEvents = False
End With
'Set reference to the source workbook
Set SourceWb = ActiveWorkbook
'Create the body text in the strbody string
strbody = "<FONT size=""3"" face=""Calibri"">"
strbody = strbody & "Hello:" & "<br>" & "<br>" & _
"XXXXXXX" & "<br>" & _
" " & "<br>" & _
"XXXXXXX" & "<br>" & _
" " & "<br>" & _
"XXXXXXX"
strbody = strbody & "</FONT>"
'Copy the ActiveSheet to a new workbook
ActiveSheet.Copy
Set DestWb = ActiveWorkbook
'Delete the button on the one sheet workbook
On Error Resume Next
DestWb.Sheets(1).DrawingObjects.Visible = True
DestWb.Sheets(1).DrawingObjects.Delete
On Error GoTo 0
'Enter the name of the file just created
TempFileName = "XXXXXXX" & " " _
& Range("A2") & " " & Format(Now, "mmm-dd-yy")
'Call the MailWithMac function to save the new file and create the mail
MailWithMac _
subject:="XXXXXXX", _
mailbody:=strbody, _
toaddress:=Range("A3"), _
ccaddress:="", _
bccaddress:="", _
displaymail:=True, _
accounttype:="", _
accountname:="", _
attachment:=TempFileName, _
FileFormat:=SourceWb.FileFormat
With Application
'.ScreenUpdating = True
.EnableEvents = True
End With
'Minimize Outlook
RunMyScript = AppleScriptTask("ExcelOutlook.scpt", "Mini", _
"/Library/Application Scripts/com.microsoft.Excel/ExcelOutlook.scpt")
'Turn on Automatic Calculation
Application.Calculation = xlCalculationAutomatic
'Turn Alert Messages On
Application.DisplayAlerts = True
End Sub
Function MailWithMac(subject As String, mailbody As String, _
toaddress As String, ccaddress As String, _
bccaddress As String, displaymail As Boolean, _
accounttype As String, accountname As String, _
attachment As String, FileFormat As Long)
'Function to create a mail with the activesheet
Dim FileExtStr As String, FileFormatNum As Long
Dim TempFilePath As String, fileattachment As String
Dim ScriptStr As String, RunMyScript As String
Select Case FileFormat
Case 52: FileExtStr = ".xlsx": FileFormatNum = 52
Case 53:
If ActiveWorkbook.HasVBProject Then
FileExtStr = ".xlsm": FileFormatNum = 53
Else
FileExtStr = ".xlsx": FileFormatNum = 52
End If
Case 57: FileExtStr = ".xls": FileFormatNum = 57
Case Else: FileExtStr = ".xlsb": FileFormatNum = 51
End Select
'Save the new temporary workbook and close it
TempFilePath = _
MacScript("return POSIX path of (path to home folder) as string")
With ActiveWorkbook
.SaveAs TempFilePath & attachment & FileExtStr, FileFormat:=FileFormatNum
.Close SaveChanges:=False
End With
'Build the AppleScriptTask parameter string
fileattachment = TempFilePath & attachment & FileExtStr
ScriptStr = subject & ";" & mailbody & ";" & toaddress & ";" & ccaddress & ";" & _
bccaddress & ";" & displaymail & ";" & accounttype & ";" & _
accountname & ";" & fileattachment
'Call the ExcelOutlook Script with the AppleScriptTask Function
RunMyScript = AppleScriptTask("ExcelOutlook.scpt", "CreateMailinOutlook", CStr(ScriptStr))
'Delete the file we just mailed
KillFile fileattachment
End Function
Function CheckScript(ScriptFileName As String) As Boolean
'Function to Check if the AppleScriptTask script file exists
Dim AppleScriptTaskFolder As String
Dim TestStr As String
AppleScriptTaskFolder = MacScript("return POSIX path of (path to desktop folder) as string")
AppleScriptTaskFolder = Replace(AppleScriptTaskFolder, "/Desktop", "") & _
"Library/Application Scripts/com.microsoft.Excel/"
On Error Resume Next
TestStr = Dir(AppleScriptTaskFolder & ScriptFileName, vbDirectory)
On Error GoTo 0
If TestStr = vbNullString Then
CheckScript = False
Else
CheckScript = True
End If
End Function
Function KillFile(Filestr As String)
'Function to Kill File
Dim ScriptToKillFile As String
Dim Fstr As String
'Delete files from a Mac using Applescript to avoid probelsm with long file names
If Val(Application.Version) < 15 Then
ScriptToKillFile = "tell applicatoin " & Chr(34) & _
"Finder" & Chr(34) & Chr(13)
ScriptToKillFile = ScriptToKillFile & _
"do shell script ""rm"" & quoted form of posix path of " & _
Chr(34) & Filestr & Chr(34) & Chr(13)
ScriptToKillFile = ScriptToKillFile & "end tell"
On Error Resume Next
MacScript (ScriptToKillFile)
On Error GoTo 0
Else
Fstr = MacScript("return POSIX path of (" & _
Chr(34) & Filestr & Chr(34) & ")")
On Error Resume Next
Kill Fstr
End If
End Function
Applescript:
on CreateMailInOutlook(paramString)
set {fieldValue1, fieldValue2, fieldValue3, fieldValue4, fieldValue5, fieldValue6, fieldValue7, fieldValue8, fieldValue9} to SplitString(paramString, ";")
tell application "Microsoft Outlook"
if fieldValue7 = "pop" then
set theAccount to the first pop account whose name is fieldValue8
set NewMail to (make new outgoing message with properties {subject:fieldValue1, content:fieldValue2, account:theAccount})
else if fieldValue7 = "imap" then
set theAccount to the first imap account whose name is fieldValue8
set NewMail to (make new outgoing message with properties {subject:fieldValue1, content:fieldValue2, account:theAccount})
else
set NewMail to (make new outgoing message with properties {subject:fieldValue1, content:fieldValue2})
end if
tell NewMail
repeat with toRecipient in my SplitString(fieldValue3, ",")
make new to recipient at end of to recipients with properties {email address:{address:contents of toRecipient}}
end repeat
repeat with toRecipient in my SplitString(fieldValue4, ",")
make new to recipient at end of cc recipients with properties {email address:{address:contents of toRecipient}}
end repeat
repeat with toRecipient in my SplitString(fieldValue5, ",")
make new to recipient at end of bcc recipients with properties {email address:{address:contents of toRecipient}}
end repeat
make new attachment with properties {file:POSIX file fieldValue9 as alias}
if fieldValue6 as boolean = true then
open NewMail
activate NewMail
else
send NewMail
end if
end tell
end tell
end CreateMailInOutlook
on SplitString(TheBigString, fieldSeparator)
tell AppleScript
set oldTID to text item delimiters
set text item delimiters to fieldSeparator
set theItems to text items of TheBigString
set text item delimiters to oldTID
end tell
return theItems
end SplitString
on Mini()
tell application "Microsoft Outlook"
tell (windows whose id is not (get id of front window) and visible is true)
set miniaturized to true
end tell
end tell
end Mini

Define file name via macro

I have the following piece of code to save a pdf file from an existing excel file.
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = ThisWorkbook.FullName
If FSO.FileExists(s(0)) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF,_
_ Filename:=sNewFilePath, Quality:=xlQualityStandard,_
_ IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
Since the code has to be run recursively, I'd would like add to the file name the week number, contained in a given cell (B2) in the sheet.
I tried replacing
s(0) = ThisWorkbook.FullName & Cells(2,2)
but it is not working. Where is the error?
FullName property returns the full path & filename & extension. Appending Cells(2,2) to that will give you a value like "c:\path\to\filename.xlsx" & Cells(2,2).Value.
You need to insert the week number (Cells(2,2)) before the file extension part.
You can probably do that like so:
sNewFilePath = Replace(s(0), s(1), Cells(2,2).Value & ".pdf")
Or, without using FileSystemObject:
Dim fullName As String, weekNum As String
Dim sNewFilePath As String
weekNum = Cells(2,2).Value
fullName = ThisWorkbook.FullName
'If the file exists, the `Dir` function will return the filename, len != 0
If Len(Dir(fullName)) <> 0 Then
'remove the extension using Mid/InstrRev functions, _
build the new filename with weeknumber & pdf extension
sNewFilePath = Mid(fullName, 1, InstrRev(fullName,".")-1) & weekNum & ".pdf"
'Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF,_
_ Filename:=sNewFilePath, Quality:=xlQualityStandard,_
_ IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
FullName includes the file extension. Perhaps this (you would be better off adding a sheet reference to B2 also).
s(0)=split(ThisWorkbook.FullName, ".")(0) & Cells(2, 2) & ".pdf"
Something like this would do it (I cleaned it up a little bit):
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Sub SavePDF()
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = ThisWorkbook.FullName
If FSO.FileExists(s(0)) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Left(s(0), InStrRev(s(0), "\")) & ".pdf"
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
sNewFilePath & Sheets("wsTakeOff").Range("AY2").Value & " - " & Sheets("wsTakeOff").Range("D1") & ".pdf", Quality:= _
xlQualityStandard, includedocproperties:=False, ignoreprintareas:=False, _
openafterpublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
End Sub

Trouble adding multiple images to an e-mail

I have an e-mail that is generated through Excel with VBA. This e-mail includes two embedded pictures in the body of the e-mail along with the separate hyperlinks to the videos they refer to. The problem is that it isn't recognizing the second picture and just embedding the same picture twice, however the hyperlinks are correct. Below is a sample of my code:
Private Sub SubmitBtn_Click()
Dim Source As Range
Dim Dest As Workbook
Dim wb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim OutApp As Object
Dim OutMail As Object
Dim MemNme As String, Email As String, UsrName As String, domainID As String, pic As String, pic2 As String
Dim Hlink As String, Hlink2 As String
State = Screener.StateBox
If State = "California" Then
If Screener.MktPlcBox = True Then
pic = "websitewithpicture1"
Hlink = "videolink"
count = 1
End If
If Screener.SubsidyBox = True Then
pic2 = "websitewithpicture2"
Hlink2 = "videolink"
count = 2
End If
With OutMail
.To = Email
.CC = ""
.BCC = ""
.Subject = "Helpful Video"
.HTMLBody = "Dear " & MemNme & ",<br><br>" _
& vbNewLine & vbNewLine & "Thank you for speaking with me today about your plan. You have a lot of choices, " _
& " and <b>we appreciate you choosing company</b>. Helping you understand your plan is important to us and I thought this video would be valuable to you.<br><br>" _
& vbNewLine & "<center><a href=" & Hlink & "<img src=cid:" & Replace(pic, " ", " ", "520") & " height =250 width=400></a>" _
& "<a href=" & Hlink2 & "<img src=cid:" & Replace(pic2, " ", " ", "420") & " height =250 width=400></a></center><br>" _
& vbNewLine & vbNewLine & "You can always get additional information at <b>website.com</b> or by calling the number on the back of your card.<br><br>" _
& vbNewLine & vbNewLine & "Thank you,<br>" _
& vbNewLine & UsrName
.Attachments.Add pic, olByValue, 0
.Attachments.Add pic2, olByValue, 0 <--------It doesn't "See" this pic???
' MsgBox "Press ok to create your e-mail"
.Display 'or use .Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Unload Me
End Sub

Resources