VBA: ADODB: get the values from RECSET.Fields - excel

My code is posted below. I can't get the values in ranges "test2" and "test3". I have only the value in range "test". Do I need to modify the code ?
Thank you very much for your suggestions !
Public Sub INFO_PROTO(NO_POLICE As String)
Dim RECSET As New ADODB.Recordset
RECSET.Open "select proto.b_perf_cma as b_perf_cma, proto.b_perf_supp_ann as b_perf_supp_ann, proto.b_perf_ctrat_gar as b_perf_ctrat_gar from db_dossier sousc, db_produit prod, db_protocole proto" & _
" where sousc.no_police = '" & NO_POLICE & "' and sousc.cd_dossier = 'SOUSC' and sousc.lp_etat_doss not in ('ANNUL','A30','IMPAY') and sousc.is_produit = prod.is_produit and sousc.is_protocole = proto.is_protocole ", cnn_Pegase, adOpenDynamic, adLockBatchOptimistic
If Not RECSET.EOF Then
Worksheets("1 - Feuille de Suivi Commercial").Range("test").Value = RECSET.Fields("b_perf_cma").Value
Worksheets("1 - Feuille de Suivi Commercial").Range("test2").Value = RECSET.Fields("b_perf_supp_ann").Value
Worksheets("1 - Feuille de Suivi Commercial").Range("test3").Value = RECSET.Fields("b_perf_ctrat_gar").Value
Else
Worksheets("1 - Feuille de Suivi Commercial").Range("test").Value = "NC"
Worksheets("1 - Feuille de Suivi Commercial").Range("test2").Value = "NC"
Worksheets("1 - Feuille de Suivi Commercial").Range("test3").Value = "NC"
End If
RECSET.Close
End Sub

Try this - it will replace any empty values with zeros
Public Sub INFO_PROTO(NO_POLICE As String)
Dim RECSET As New ADODB.Recordset
RECSET.Open "select proto.b_perf_cma as b_perf_cma, proto.b_perf_supp_ann as " & _
" b_perf_supp_ann, proto.b_perf_ctrat_gar as b_perf_ctrat_gar " & _
"from db_dossier sousc, db_produit prod, db_protocole proto" & _
" where sousc.no_police = '" & NO_POLICE & "' and sousc.cd_dossier = 'SOUSC' " & _
" and sousc.lp_etat_doss not in ('ANNUL','A30','IMPAY') and " & _
"sousc.is_produit = prod.is_produit and sousc.is_protocole = proto.is_protocole ", _
cnn_Pegase, adOpenDynamic, adLockBatchOptimistic
'use a With block to remove repetition
With ThisWorkbook.Worksheets("1 - Feuille de Suivi Commercial")
If Not RECSET.EOF Then
.Range("test").Value = CheckValue(RECSET.Fields("b_perf_cma").Value)
.Range("test2").Value = CheckValue(RECSET.Fields("b_perf_supp_ann").Value)
.Range("test3").Value = CheckValue(RECSET.Fields("b_perf_ctrat_gar").Value)
Else
.Range("test").Value = "NC"
.Range("test2").Value = "NC"
.Range("test3").Value = "NC"
End If
End With
RECSET.Close
End Sub
Function CheckValue(v)
'Default to zero if null
CheckValue = iif(Len(v) = 0, 0, v)
End Function

Related

VBA Addod: take non empty value form the cell

I would like to take the value from C6 for my sql query. But, I would like to do it in case if C6 is not empty. I don't know how translate this option in my code. My code is :
Public Sub INFO_PROTO34(ByRef strQ As String)
Dim RECSET As New ADODB.Recordset
RECSET.Open "select proto.b_perf_cma as b_perf_cma, proto.b_perf_supp_ann as b_perf_supp_ann, proto.b_perf_ctrat_gar as b_perf_ctrat_gar from db_dossier sousc,db_produit prod, db_protocole proto" & _
" where sousc.no_police = Range("C6") and sousc.cd_dossier = 'SOUSC' and sousc.lp_etat_doss not in ('ANNUL','A30','IMPAY') and sousc.is_produit = prod.is_produit and '" & strQ & "' = proto.is_protocole ", cnn_Pegase, adOpenDynamic, adLockBatchOptimistic
If Not RECSET.EOF Then
Worksheets("1 - Feuille de Suivi Commercial").Range("Calcul_Perf_Contrat_et_Orient").Value = RECSET.Fields("b_perf_ctrat_gar").Value
Else
Worksheets("1 - Feuille de Suivi Commercial").Range("Calcul_Perf_Contrat_et_Orient").Value = "0"
End If
RECSET.Close
End Sub
Thank you very much for you suggestions
For example:
Public Sub INFO_PROTO34(ByRef strQ As String)
Dim RECSET As New ADODB.Recordset, v
v = Range("C6").Value 'Activesheet? Really need a specific worksheet here
If Len(v) > 0 Then
RECSET.Open " select proto.b_perf_cma as b_perf_cma, proto.b_perf_supp_ann as b_perf_supp_ann, " & _
" proto.b_perf_ctrat_gar as b_perf_ctrat_gar from db_dossier sousc,db_produit prod, db_protocole proto" & _
" where sousc.no_police = " & v & " and sousc.cd_dossier = 'SOUSC' and " & _
" sousc.lp_etat_doss not in ('ANNUL','A30','IMPAY') and sousc.is_produit = prod.is_produit" & _
" and '" & strQ & "' = proto.is_protocole ", cnn_Pegase, adOpenDynamic, adLockBatchOptimistic
With Worksheets("1 - Feuille de Suivi Commercial").Range("Calcul_Perf_Contrat_et_Orient")
If Not RECSET.EOF Then
.Value = RECSET.Fields("b_perf_ctrat_gar").Value
Else
.Value = "0"
End If
End With
RECSET.Close
End If
End Sub
If sousc.no_police is not numeric then add single-quotes around the value.
Before the RECSET.OPEN you can try using the IsEmpty method
I didn't test this out on VBA script yet but here's how I'd change your code to take C6 cell into account depending if its blank or not:
Public Sub INFO_PROTO34(ByRef strQ As String)
Dim RECSET As New ADODB.Recordset
if IsEmpty(Range("C6").value) = true then
' if C6 cell is blank or empty it will do the SQL without the C6 cell value
RECSET.Open "select proto.b_perf_cma as b_perf_cma, proto.b_perf_supp_ann as b_perf_supp_ann, proto.b_perf_ctrat_gar as b_perf_ctrat_gar from db_dossier sousc,db_produit prod, db_protocole proto" & _
" where sousc.cd_dossier = 'SOUSC' and sousc.lp_etat_doss not in ('ANNUL','A30','IMPAY') and sousc.is_produit = prod.is_produit and '" & strQ & "' = proto.is_protocole ", cnn_Pegase, adOpenDynamic, adLockBatchOptimistic
Else
' in this case the cell C6 is not empty/blank so it will use your existing SQL statement
RECSET.Open "select proto.b_perf_cma as b_perf_cma, proto.b_perf_supp_ann as b_perf_supp_ann, proto.b_perf_ctrat_gar as b_perf_ctrat_gar from db_dossier sousc,db_produit prod, db_protocole proto" & _
" where sousc.no_police = Range("C6") and sousc.cd_dossier = 'SOUSC' and sousc.lp_etat_doss not in ('ANNUL','A30','IMPAY') and sousc.is_produit = prod.is_produit and '" & strQ & "' = proto.is_protocole ", cnn_Pegase, adOpenDynamic, adLockBatchOptimistic
end if
If Not RECSET.EOF Then
Worksheets("1 - Feuille de Suivi Commercial").Range("Calcul_Perf_Contrat_et_Orient").Value = RECSET.Fields("b_perf_ctrat_gar").Value
Else
Worksheets("1 - Feuille de Suivi Commercial").Range("Calcul_Perf_Contrat_et_Orient").Value = "0"
End If
RECSET.Close
End Sub
See https://www.techonthenet.com/excel/formulas/isempty.php for more information on the IsEmpty method.

Getting the value from cell

I want to get the value (T28200006) from Range("C6").
I get this error:
Public Sub INFO_PROTO1(ByRef strQ As String)
Dim RECSET As New ADODB.Recordset, numero_de_police
If Len(numero_de_police) > 0 Then
RECSET.Open " select sousc.is_produit as b_perf_cma from db_dossier sousc,db_produit prod, db_protocole proto" & _
" where sousc.no_police = " & numero_de_police & " and sousc.cd_dossier = 'SOUSC' and " & _
" sousc.lp_etat_doss not in ('ANNUL','A30','IMPAY') and sousc.is_produit = prod.is_produit ", cnn_Pegase, adOpenDynamic, adLockBatchOptimistic
With Worksheets("1 - Feuille de Suivi Commercial").Range("Calcul_CMA_Origine")
Your query value is not a number, so you need to quote it in your SQL:
..." where sousc.no_police = '" & numero_de_police & "' and...

Include the value of each not empty cell to a message

I'd like to include the value of each not empty cell in the message to send, but I don't know which is the good syntax to use?
Private Sub CommandButton6_Click()
Dim MailAd As String
Dim Msg As String
Dim Subj As String
Dim URLto As String
Dim Nom As String
Nom = "User name"
Dim Pole As String
Pole = " POLE"
Dim Texte As String
Texte = " Thanks for the informations you send to me "
'Sélectionne la cellule correspondant à l'adresse mail de la ligne :
If ComboBox1.ListIndex <> -1 Then Cells(ComboBox1.ListIndex + 2, 8).Select
'Le mail est adressé sur la base de la cellule active :
MailAd = TextBox7
Range("A2:J32").Select
Selection.Copy
Dim StrBody As String
StrBody = Sheets("FICHIER ADRESSES").Range("A2").Value
'Copie = TextBox.2 'bien mentionner le n° de la texbox
Subj = "Message à l'attention de " 'Objet du message automatique mais on peut faire réféence à une TextBox
Msg = Msg & "Bonjour " & TextBox2.Text & ",%0D%0A %0D%0A" 'Corps du message
'Msg = Msg & "Bonjour " & Selection.Insert & ",%0D%0A %0D%0A"
Msg = Msg & Texte & StrBody & ",%0D%0A %0D%0A" & Nom & Pole & "%0D%0A %0D%0A" 'Corps du message
URLto = "mailto:" & MailAd & "?subject=" & Subj & "&body=" & Msg & "&Cc=" '& copie
ActiveWorkbook.FollowHyperlink Address:=URLto
End Sub
Presuming you are talking about the range A2:J32 and want the values to show in your "msg" string: (this is untested)
Private Sub CommandButton6_Click()
Dim MailAd As String
Dim Msg As String
Dim Subj As String
Dim URLto As String
Dim Nom As String
Nom = "User name"
Dim Pole As String
Pole = " POLE"
Dim Texte As String
Texte = " Thanks for the informations you send to me "
'Sélectionne la cellule correspondant à l'adresse mail de la ligne :
If ComboBox1.ListIndex <> -1 Then Cells(ComboBox1.ListIndex + 2, 8).Select
'Le mail est adressé sur la base de la cellule active :
MailAd = TextBox7
Range("A2:J32").Select
Dim rngCell as Range, sNonEmpty as string
For each rngCell in Range("A2:J32")
if rngcell.value <> "" then snonempty = _
iif(snonempty="",rngcell.value,snonempty & ", " & rngcell.value)
Next
Selection.Copy
Dim StrBody As String
StrBody = Sheets("FICHIER ADRESSES").Range("A2").Value
'Copie = TextBox.2 'bien mentionner le n° de la texbox
Subj = "Message à l'attention de " 'Objet du message automatique mais on peut faire réféence à une TextBox
Msg = Msg & "Bonjour " & TextBox2.Text & ",%0D%0A %0D%0A" 'Corps du message
'Msg = Msg & "Bonjour " & Selection.Insert & ",%0D%0A %0D%0A"
Msg = Msg & Texte & StrBody & ",%0D%0A %0D%0A" & Nom & Pole & "%0D%0A %0D%0A" & VBNEWLINE & _
"YOUR VALUES: " & sNonEmpty 'Corps du message
URLto = "mailto:" & MailAd & "?subject=" & Subj & "&body=" & Msg & "&Cc=" '& copie
ActiveWorkbook.FollowHyperlink Address:=URLto
End Sub

Sending Multiple emails with Different Attachments

I am trying to send emails to a list of recipients in an Excel spreadsheet, with a different attachment for each of the emails.
I created a macro that generates the different emails, but when I added attachments, only the first email of the list is created with the correct attachment.
When the loop comes back to the second email it gives me an error message saying that the attachment was not found (I assume this is for the second message).
I checked and the file names and paths are correct according to the rules I set in the code. It doesn't create a draft of the second email, but simply tells me the file was not found.
How can I generate all of the emails with their proper attachments?
The code is as follows:
Sub clientemails()
Dim pfolio As String
Dim destino As String
Dim mo As String
Dim text As String
Dim subject As String
Dim CC As String
Dim signature As String
Dim officer As String
Dim yr As String
Dim date1 As String
Dim position As String
Dim analysis As String
Dim activities As String
Dim nl As Integer
Dim i As Integer
Dim OutlookApp As Outlook.Application
Dim MItem As Outlook.mailitem
Set OutlookApp = New Outlook.Application
nl = Cells(5, 1).End(xlDown).Row
i = 5
yr = Cells(1, 6).Value
date1 = Format(Cells(1, 4).Value, "mm.dd.yy")
While nl + 1 > i
pfolio = Cells(i, 2).Value
destino = Cells(i, 3).Value
officer = Cells(i, 10).Value
CC = Cells(i, 11).Value
Set MItem = OutlookApp.CreateItem(olmailitem)
If Cells(i, 9) = "P" Then
mo = Cells(1, 3)
subject = "Posição e Análise " & pfolio
text = "<p><font face=arial size=3>Bom Dia,</p>" _
& "<p>Segue em anexo a posição e análise da carteira " & pfolio & " referente ao mês de " & mo & ". Caso tenha quaisquer dúvidas, favor entrar em contato conosco.</p>" _
& "Atenciosamente,"
ElseIf Cells(i, 9) = "E" Then
month = Cells(2, 3)
subject = pfolio & " Statement and Analysis"
text = "<p><font face=arial size=3>Hello,</p>" _
& "<p>Please find attached the portfolio statement and analysis for the " & pfolio & " portfolio for the month of " & mo & ". Should you have any questions, please don't hesitate to contact us.</p>" _
& "Sincerely,"
End If
If Cells(i, 4) = "X" Then
position = "F:\Files\General Folders\3 Clients\" & officer & "\" & pfolio & "\Position\" & yr & "\" & pfolio & " Portfolio Statement Summary " & date1 & ".pdf"
With MItem
.Attachments.Add position
End With
End If
If Cells(i, 5) = "X" Then
analysis = "F:\Files\General Folders\3 Clients\" & officer & "\" & pfolio & "\Portfolio Analysis\" & yr & "\" & pfolio & " Portfolio Analysis " & date1 & ".pdf"
With MItem
.Attachments.Add analysis
End With
End If
If Cells(i, 6) = "X" Then
activities = "F:\Files\General Folders\3 Clients\" & officer & "\" & pfolio & "\Portfolio Activities\" & yr & "\" & pfolio & " Portfolio Activities " & date1 & ".pdf"
With MItem
.Attachments.Add activities
End With
End If
With MItem
.Display
End With
signature = MItem.HTMLBody
With MItem
.subject = subject
.To = destino
.CC = CC
.HTMLBody = text & signature
.Save
End With
i = i + 1
Wend
End Sub
I understand you are supposed to save your mail item before adding attachments. So you might need
MItem.SaveAs('some path name', olTXT)
before you add each attachment.
EDIT: Or perhaps it's best to simply use
MItem.Save
I recently make an library in order to send email with macros VBA. I use Microsoft CDO technology to do it, so it doesn't depend on client messagerie like Outlook or Thunderbird. It's only depend on SMTP server.
Enjoy.
'---------------------------------------------------------------------------
' Constantes and global variables
'---------------------------------------------------------------------------
Const CONFIG_ACTIVE_SEND_EMAIL = True
Const CONFIG_SMTP_SERVER As String = "smtp.host"
Const CONFIG_SMTP_PORT As String = "25"
Const CONFIG_SMTP_AUTHENTICATE = "0"
Const CONFIG_SMTP_USERNAME = "20100"
Const CONFIG_SMTP_PASSWORD = "seeyousoon"
Const CONFIG_SMTP_SSL = "false"
Dim SEND_TRACE_ACTIVATE As Boolean
Dim SEND_TRACE_EMAIL As String
Global LOG_ACTIVATE As Boolean
Global LOG_FILEPATH As String
'---------------------------------------------------------------------------
' Pour envoyer un email avec un serveur SMTP avec la technologie CDO.Message
'---------------------------------------------------------------------------
' #param String expediteur : l'expediteur de l'email
' #param String destinataires : le ou les destinataires de l'email (ex: "email1#aot.org; email2#aot.org")
' #param String sujet : le sujet de l'email
' #param String body : le contenu du message de l'email (ex: "Hello" & vbNewLine & "See you soon")
' #param Optional String carbon_copy : Addresse(s) pour Carbon-Copy (envoyer un email à plusieurs personnes)
' #param Optional String blind_carbon_copy : Idem que carbon copy sauf que dans l'en-tête la liste des personnes en copie est cachée.
' #param Optional Variant fichiers_joints : String ou Array(String) de chemin de fichiers à joindre dans l'email (max:8mo en tout)
' #param Optional Boolean opt_sendTraceActivate : pour activer la récuperation de la trace d'envoi (par défaut envoi à l'expediteur de l'email). Active forcement l'option opt_logActivate = true.
' #param Optional String opt_sendTraceEmail : pour changer l'email de reception de la trace d'envoi (par défaut envoi à l'expediteur de l'email)
' #param Optional Boolean opt_logActivate : pour activer le log
' #param Optional String opt_logFilePath : pour changer le chemin du fichier log (par defaut = Application.ActiveWorkbook.Path & "log.txt")
'---------------------------------------------------------------------------
Sub sendEmail( _
expediteur As String, _
destinataires As String, _
sujet As String, _
body As String, _
Optional carbon_copy As String = "", _
Optional blind_carbon_copy As String = "", _
Optional fichiers_joints As Variant, _
Optional opt_sendTraceActivate As Boolean = False, _
Optional opt_sendTraceEmail As String = "", _
Optional opt_logActivate As Boolean = False, _
Optional opt_logFilePath As String = "")
'-- Gestion option sendTrace
If opt_sendTraceActivate = True Then
opt_logActivate = True
SEND_TRACE_ACTIVATE = True
SEND_TRACE_EMAIL = expediteur
If Not opt_sendTraceEmail = "" Then
SEND_TRACE_EMAIL = opt_sendTraceEmail
End If
End If
'-- Gestion option log
If opt_logActivate = True Then
LOG_ACTIVATE = True
LOG_FILEPATH = Application.ActiveWorkbook.Path & "\log_email.txt"
If Not opt_logFilePath = "" Then
LOG_FILEPATH = opt_logFilePath
End If
LogFileDelete
End If
'-- Gestion option carbon_copy et blind_carbon_copy pour affichage dans le debug
Dim carbon_copy_str As String
Dim blind_carbon_copy_str As String
If carbon_copy = "" Then
carbon_copy_str = "#vide#"
End If
If blind_carbon_copy = "" Then
blind_carbon_copy_str = "#vide#"
End If
'-- Log du traitement (ne fonctionne que si l'option opt_logActivate est à true
date_now = Now()
LogInformation " "
If CONFIG_ACTIVE_SEND_EMAIL = True Then
LogInformation "---[ DEBUT DU TRAITEMENT]---"
Else
LogInformation "---[ DEBUT DU TRAITEMENT (mode simulation) ]---"
End If
LogInformation " _________________________________"
LogInformation " "
LogInformation " PADI-Excel email (v0.0.1) "
LogInformation " _________________________________"
LogInformation " "
LogInformation " * Informations *"
LogInformation " -> Macro du classeur = " & ThisWorkbook.Name
LogInformation " -> Utilisateur = " & Application.UserName
LogInformation " -> Debut traitement = " & Format(date_now, "yyyy-mm-dd hh:mm:ss")
LogInformation " -> SMTP Server = " & CONFIG_SMTP_SERVER
LogInformation " -> SMTP Port = " & CONFIG_SMTP_PORT
LogInformation " -> SMTP Username = " & CONFIG_SMTP_USERNAME
LogInformation " -> SMTP SSL = " & CONFIG_SMTP_SSL
LogInformation " -> Option sendTrace = " & SEND_TRACE_ACTIVATE
LogInformation " -> Email sendTrace = " & SEND_TRACE_EMAIL
LogInformation " "
LogInformation " * Propriétés email *"
LogInformation " -> Expediteur = " & expediteur
LogInformation " -> Destinataires = " & destinataires
LogInformation " -> Subject eMail = " & sujet
LogInformation " -> Carbon copy = " & carbon_copy_str
LogInformation " -> Blind CC = " & blind_carbon_copy_str
LogInformation " "
LogInformation " -> Body eMail:"
LogInformation "{{-------------------------------}}"
LogInformation body
LogInformation "{{-------------------------------}}"
LogInformation " "
'-- Création de l'objet CDO (pour créer en envoyer l'email + headers email)
Dim objCDO As Object
Set objCDO = CreateObject("CDO.Message")
'-- Configuration du serveur SMTP
With objCDO.Configuration.Fields
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = CONFIG_SMTP_SERVER
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = CONFIG_SMTP_PORT
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = CONFIG_SMTP_AUTHENTICATE
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = CONFIG_SMTP_SSL
End With
'-- Configuration authentification SMTP (si nécessaire)
If CONFIG_SMTP_AUTHENTICATE = "1" Then
With objCDO.Configuration.Fields
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = CONFIG_SMTP_USERNAME
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = CONFIG_SMTP_PASSWORD
End With
End If
'-- Mise à jour de la configuration CDO
objCDO.Configuration.Fields.Update
'-- Création du mail à envoyer
With objCDO
.From = expediteur
.To = destinataires
.Subject = sujet
.TextBody = body
.Cc = carbon_copy
.Bcc = blind_carbon_copy
End With
'-- Création du mail à envoyer : ajout de 1 ou plusieurs fichiers joint (si renseigné)
LogInformation " -> fichiers joints:"
LogInformation "{{-------------------------------}}"
If Not IsMissing(fichiers_joints) Then
If IsArray(fichiers_joints) Then
For i = LBound(fichiers_joints) To UBound(fichiers_joints)
objCDO.AddAttachment fichiers_joints ' "C:\temp\Bon de commande.pdf"
Next i
Else
LogInformation " 1 fichiers joints :"
LogInformation " -> " & fichiers_joints
objCDO.AddAttachment fichiers_joints ' "C:\temp\Bon de commande.pdf"
End If
Else
LogInformation "#aucun#"
End If
LogInformation "{{-------------------------------}}"
'-- Envoi de l'email
If CONFIG_ACTIVE_SEND_EMAIL = True Then
objCDO.Send
End If
LogInformation " "
LogInformation " -> email envoyé à " & Format(date_now, "yyyy-mm-dd hh:mm:ss")
LogInformation " "
LogInformation "---[ FIN DU TRAITEMENT]---"
LogInformation " "
End Sub
'----------------------------------------------------
' Ajoute un message dans le fichier log déclaré dans la variable LOG_FILEPATH
' uniquement si le log est activé avec la variable LOG_ACTIVATE
'----------------------------------------------------
' #param String logMessage : le message à ajouter dans le fichier log
'----------------------------------------------------
Sub LogInformation(logMessage As String)
If LOG_ACTIVATE = True Then
Dim FileNum As Integer
FileNum = FreeFile ' next file number
Open LOG_FILEPATH For Append As #FileNum ' creates the file if it doesn't exist
Print #FileNum, logMessage ' write information at the end of the text file
Close #FileNum ' close the file
End If
End Sub
'----------------------------------------------------
' Pour supprimer le fichier log en début de traitement
'----------------------------------------------------
Sub LogFileDelete()
On Error Resume Next ' ignore possible errors
Kill LOG_FILEPATH ' delete the file if it exists and it is possible
On Error GoTo 0 ' break on errors
End Sub
'----------------------------------------------------
' Fonction pour tester si un repertoire (ex: c:\test\foo\) existe
'----------------------------------------------------
' #param String folderPath : le répertoire à tester
' #return Boolean (true, le répertoire existe et false sinon)
'----------------------------------------------------
Function is_folder_exist(folderPath As String) As Boolean
Dim FSO As Object
Set FSO = CreateObject("scripting.filesystemobject")
If Right(folderPath, 1) <> "\" Then
folderPath = folderPath & "\"
End If
If FSO.FolderExists(folderPath) = False Then
is_folder_exist = False
Else
is_folder_exist = True
End If
End Function
'----------------------------------------------------
' Fonction pour tester si un fichier (ex: c:\test\foo\sample.txt) existe
'----------------------------------------------------
' #param String filePath : le fichier à tester
' #return Boolean (true, le répertoire existe et false sinon)
'----------------------------------------------------
Function is_file_exist(filePath As String) As Boolean
Dim FSO As Object
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FileExists(filePath) = False Then
is_file_exist = False
Else
is_file_exist = True
End If
End Function
Example of use it :
sendEmail _
"from_email#acme.com", _
"to_email#acme.com", _
"Subjet", _
"Hello," & vbCrLf & "rfxc", _
opt_logActivate:=True, _
fichiers_joints:="c:\test1.pdf"

Run-time error 5 in excel while saving a word document as a pdf

So I've been running this code on a couple computers for awhile. However, the spreadsheet has begun to crash and refuses to save, so I created a new one, with everything the same. It crashes as I try and save my word document as a PDF, specifically, this line
wrdDoc.ExportAsFixedFormat OutputFileName:=Path & "Lot " & Lot_Number & " " & Address & " " & Suburb & " " & Job & " - s40" & ".pdf", _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, Range:=wdExportAllDocument, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
Here is my full code, My apologies for lack of comments etc, it was written to be used only by me.
Sub AutoFill()
ScreenUpdating = False
Dim Job As String
Dim Rail As String
Dim Panel_Type As String
Dim Address As String
Dim Lot_Number As Integer
Dim Suburb As String
Dim Town As String
Dim Town_Check As String
Dim Current_Date As String
Dim DTC As String
Dim WordFileName As String
Dim Path As String
Dim i As Integer
Dim wrdApp As Object
Dim wrdDoc As Object
Dim count As Integer
count = Range("Solarcount")
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
wrdApp.DisplayAlerts = wdAlertsNone
For i = 1 To count
Job = Range("WordArray").Cells(i, 1)
Rail = Range("WordArray").Cells(i, 2)
Panel_Type = Range("WordArray").Cells(i, 3)
Lot_Number = Range("WordArray").Cells(i, 4)
Suburb = Range("WordArray").Cells(i, 7)
Address = Range("WordArray").Cells(i, 11)
Town = Range("WordArray").Cells(i, 10)
Town_Check = Range("WordArray").Cells(i, 12)
Current_Date = Range("WordArray").Cells(i, 14)
DTC = Range("WordArray").Cells(i, 15)
Path = Range("Path")
Select Case Rail
Case "Blue Sun"
WordFileName = Range("FileNames").Cells(1, 1)
Case "Clenergy"
WordFileName = Range("FileNames").Cells(2, 1)
Case "Conergy"
WordFileName = Range("FileNames").Cells(3, 1)
Case "Sunlock"
WordFileName = Range("FileNames").Cells(4, 1)
End Select
Set wrdDoc = wrdApp.Documents.Open(Path & WordFileName, , True)
With wrdDoc
With .Bookmarks
.Item("Address").Range = Address
.Item("Current_date").Range = Current_Date
.Item("Job_1").Range = Job
.Item("Job_2").Range = Job
.Item("Lot_Number").Range = Lot_Number
.Item("Panel_Type").Range = Panel_Type
.Item("Panel_Type_2").Range = Panel_Type
.Item("Suburb").Range = Suburb
.Item("Town").Range = Town
.Item("Town_check").Range = Town_Check
If Customer = "Sunlock" Then
.Item("DTC").Range = DTC
End If
End With
wrdDoc.SaveAs (Path & "Lot " & Lot_Number & " " & Address & " " & Suburb & " " & Job & " - s40" & ".doc")
wrdDoc.ExportAsFixedFormat OutputFileName:=Path & "Lot " & Lot_Number & " " & Address & " " & Suburb & " " & Job & " - s40" & ".pdf", _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, Range:=wdExportAllDocument, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
.Close ' close the document
End With
Next
wrdApp.Quit ' close the Word application
Set wrdDoc = Nothing
Set wrdApp = Nothing
ScreenUpdating = True
End Sub
Solved it.
Needed to include the Microsoft Word 14.0 Object Library

Resources