I use a code to generate pdf and to merge with others pdfs. But the pdfs I merge are upside down. The original pdfs are right side up. All codes and functions are here in the order of process.
Code saving originals in a file and create one with all merged using pdfforge.
Edit : I reduce my code here, first I get the different pdfs, second I launch functions to merge its.
recuperer_PJ strChemin3, "Ticket", "Ticket_FO_Documents", "(((Ticket.[Ticket_FO_Numéro ticket])='" & Me![Ticket_FO_Numéro ticket] & "'))"
recuperer_PJ strChemin3, "Ticket", "Ticket_FO_Justificatif_Delegation", "(((Ticket.[Ticket_FO_Numéro ticket])='" & Me![Ticket_FO_Numéro ticket] & "'))"
recuperer_PJ strChemin3, "Ticket", "[Ticket_FO_Pièces jointes]", "(((Ticket.[Ticket_FO_Numéro ticket])='" & Me![Ticket_FO_Numéro ticket] & "'))"
recuperer_PJ strChemin3, "Ticket", "Ticket_MO_Documents", "(((Ticket.[Ticket_FO_Numéro ticket])='" & Me![Ticket_FO_Numéro ticket] & "'))"
recuperer_PJ strChemin3, "Ticket", "Ticket_BO_Documents", "(((Ticket.[Ticket_FO_Numéro ticket])='" & Me![Ticket_FO_Numéro ticket] & "'))"
recuperer_PJ strChemin3, "Ticket", "Ordre_Justificatif_Validation", "(((Ticket.[Ticket_FO_Numéro ticket])='" & Me![Ticket_FO_Numéro ticket] & "'))"
recuperer_PJ strChemin3, "Ticket", "Ticket_BO_Documents_Conformité", "(((Ticket.[Ticket_FO_Numéro ticket])='" & Me![Ticket_FO_Numéro ticket] & "'))"
'Fusion des PJ
PilotageMacro1 strChemin3, strChemin2 & "\" & Me![Ticket_FO_Numéro ticket] & " - " & Me!Titre & ".pdf"
FileMove strChemin2 & "\" & Me![Ticket_FO_Numéro ticket] & " - " & Me!Titre & ".pdf", strChemin3 & "\" & Me![Ticket_FO_Numéro ticket] & " - " & Me!Titre & " initial complet.pdf"
function to save and launch the "mergage"
Public Sub recuperer_PJ(ByVal strNomDestination As String, ByVal strTable As String, ByVal strChamp As String, ByVal strWhere As String)
Dim rst1 As DAO.Recordset
Dim rst2 As DAO.Recordset
Dim strSQL As String
' Se positionner sur l'enregistrement souhaité
strSQL = "SELECT * FROM " & strTable & " WHERE" & strWhere & ";"
Set rst1 = CurrentDb.OpenRecordset(strSQL, dbOpenSnapshot)
' Obtenir le "sous-recordset" des pièces jointes
Set rst2 = rst1(strChamp).Value
' Lister les pièces jointes
While Not rst2.EOF
test = 0
dossier = strNomDestination & "\"
Do While Not test = 1
txt = Dir(dossier & rst2.Fields("FileName"))
If txt = "" Then
test = 1
Else
dossier = dossier & "_"
End If
Loop
dossier = dossier & rst2.Fields("FileName")
rst2.Fields(0).SaveToFile dossier
rst2.MoveNext
Wend
' On ferme les 2 Recordsets
rst2.Close
Set rst2 = Nothing
rst1.Close
Set rst1 = Nothing
End Sub
functions to merge
Public Sub PilotageMacro1(ByVal dossierFusion As String, ByVal dossierSortie As String)
Dim Xl As Excel.Application
Dim wbk As Excel.Workbook
' Démarrer Excel et le rendre visible
Set Xl = New Excel.Application
Xl.Visible = False
' Ouvrir le classeur qui contient les macros
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT [Lien PDF] FROM Paramêtres")
Lien_PDF = rs.Fields(0)
Set wbk = Xl.Workbooks.Open(Lien_PDF & ".xlsm")
'Set wbk = xl.Workbooks.Open(Lien_Dossier_Tickets & "\A_ne_pas_supprimer_G2T.xlsm")
' Exécuter une macro
Xl.Run "SelDossierFusion", dossierFusion, dossierSortie
' Fermer le classeur sans l'enregistrer
wbk.Close False
Set wbk = Nothing
' Quitter Excel
Xl.Quit
Set Xl = Nothing
End Sub
Option Explicit
Dim Cpt As Long
Dim Tableau() As Variant
Const TypeFichier As String = "*.pdf"
Private Sub Fusion(ByVal dossierSortie As String)
Dim Pdf As Object
Set Pdf = CreateObject("pdfforge.pdf.pdf")
Pdf.MergePDFFiles_2 Tableau, dossierSortie, True
Set Pdf = Nothing
End Sub
Private Sub ListeFichiers(ByVal sChemin As String, ByVal Recursif As Boolean)
Dim FSO As Object
Dim Dossier As Object
Dim SousDossier As Object
Dim Fichier As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Dossier = FSO.GetFolder(sChemin)
For Each Fichier In Dossier.Files
If UCase(Fichier.Name) Like UCase(TypeFichier) Then
ReDim Preserve Tableau(Cpt)
Tableau(Cpt) = Fichier.Path
Cpt = Cpt + 1
Application.StatusBar = Cpt
End If
Next Fichier
If Recursif Then
For Each SousDossier In Dossier.SubFolders
ListeFichiers SousDossier.Path, True
Next SousDossier
End If
Set Dossier = Nothing
Set FSO = Nothing
End Sub
Sub SelDossierFusion(ByVal dossierFusion As String, ByVal dossierSortie As String)
Dim sChemin As String
Dim FSO As Object
Dim Dossier As Object
sChemin = dossierFusion
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Dossier = FSO.GetFolder(sChemin)
' ListeFichiers récursive ou non True/False
ListeFichiers Dossier, True
Fusion (dossierSortie)
Set FSO = Nothing
End Sub
Related
I have a code which can transfer the Excel files from one folder to another but i would like to update the code so that it can move all the files (.xml, .txt, .pdf, etc.) from one folder to another.
Sub MoveFiles()
Dim sourceFolderPath As String, destinationFolderPath As String
Dim FSO As Object, sourceFolder As Object, file As Object
Dim fileName As String, sourceFilePath As String, destinationFilePath As String
Application.ScreenUpdating = False
sourceFolderPath = "E:\Source"
destinationFolderPath = "E:\Destination"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set sourceFolder = FSO.GetFolder(sourceFolderPath)
For Each file In sourceFolder.Files
fileName = file.Name
If InStr(fileName, ".xlsx") Then ' Only xlsx files will be moved
sourceFilePath = file.Path
destinationFilePath = destinationFolderPath & "\" & fileName
FSO.MoveFile Source:=sourceFilePath, Destination:=destinationFilePath
End If ' If InStr(sourceFileName, ".xlsx") Then' Only xlsx files will be moved
Next
'Don't need set file to nothing because it is initialized in for each loop
'and after this loop is automatically set to Nothing
Set sourceFolder = Nothing
Set FSO = Nothing
End Sub
can you please help
Move Files Using MoveFile
You would get greater control of things by using CopyFile and DeleteFile instead of MoveFile.
Using Dir, FileCopy, and Kill, instead of the FileSystemObject object and its methods, would make it simpler and also faster.
Option Explicit
Sub MoveFilesTEST()
Const sFolderPath As String = "E:\Source"
Const dFolderPath As String = "E:\Destination"
Const FilePattern As String = "*.*"
MoveFiles sFolderPath, dFolderPath, FilePattern
End Sub
Sub MoveFiles( _
ByVal SourceFolderPath As String, _
ByVal DestinationFolderPath As String, _
Optional ByVal FilePattern As String = "*.*")
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(SourceFolderPath) Then
MsgBox "The source folder path '" & SourceFolderPath _
& "' doesn't exist.", vbCritical
Exit Sub
End If
If Not fso.FolderExists(DestinationFolderPath) Then
MsgBox "The destination folder path '" & DestinationFolderPath _
& "' doesn't exist.", vbCritical
Exit Sub
End If
Dim apSep As String: apSep = Application.PathSeparator
Dim sPath As String: sPath = SourceFolderPath
If Left(sPath, 1) <> apSep Then sPath = sPath & apSep
Dim sFolder As Object: Set sFolder = fso.GetFolder(sPath)
If sFolder.Files.Count = 0 Then
MsgBox "There are no files in the source folder '" & sPath & "'.", _
vbExclamation
Exit Sub
End If
Dim dPath As String: dPath = DestinationFolderPath
If Left(dPath, 1) <> apSep Then dPath = dPath & apSep
Dim dFolder As Object: Set dFolder = fso.GetFolder(dPath)
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
Dim sFile As Object
Dim dFilePath As String
Dim ErrNum As Long
Dim MovedCount As Long
Dim NotMovedCount As Long
For Each sFile In sFolder.Files
dFilePath = dPath & sFile.Name
If fso.FileExists(dFilePath) Then
dict(sFile.Path) = Empty
NotMovedCount = NotMovedCount + 1
Else
On Error Resume Next
fso.MoveFile sFile.Path, dFilePath
ErrNum = Err.Number
' e.g. 'Run-time error '70': Permission denied' e.g.
' when the file is open in Excel
On Error GoTo 0
If ErrNum = 0 Then
MovedCount = MovedCount + 1
Else
dict(sFile.Path) = Empty
NotMovedCount = NotMovedCount + 1
End If
End If
Next sFile
Dim Msg As String
Msg = "Files moved: " & MovedCount & "(" & NotMovedCount + MovedCount & ")"
If NotMovedCount > 0 Then
Msg = Msg & vbLf & "Files not moved:" & NotMovedCount & "(" _
& NotMovedCount + MovedCount & ")" & vbLf & vbLf _
& "The following files were not moved:" & vbLf _
& Join(dict.keys, vbLf)
End If
MsgBox Msg, IIf(NotMovedCount = 0, vbInformation, vbCritical)
End Sub
I have a macro in an Excel Workbook, that is connected to a button that says Export
When I click the button, it triggers the Export XML dialog and I have to manually search for a folder to export it into and enter the filename.
Since the folders in my Documents are named exactly the same as the value of the Cell A24, i would like it to direct itself into the correct folder and suggest me a filename based on the value of the Cell A24 with some extra text behind it.
So far i have this in the VBA:
Public Sub ExportToXML()
Dim strFilePath As String
Dim POFilePath As String
Dim FOFilePath As String
Dim POFileName As String
Dim FOFileName As String
Dim XMLDoc As MSXML2.DOMDocument
Dim xNode As MSXML2.IXMLDOMNode
Dim xAttribute As MSXML2.IXMLDOMAttribute
Dim xElement As MSXML2.IXMLDOMElement
Dim xElementRoot As MSXML2.IXMLDOMElement
Application.ScreenUpdating = False
MainSheetName = ActiveSheet.Name
POFilePath = "C:\Users\admin\Desktop\" & Range("A24")
FOFilePath = "C:\Users\admin\Desktop\" & Range("D22") & " " & Range("A22")
POFileName = "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
FOFileName = "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
If Range("A24").value = "0" Then
strFilePath = Application.GetSaveAsFilename(FOFilePath & FOFileName, fileFilter:="XML files (*.xml),*.xml", Title:="Save FileAs...")
Else
strFilePath = Application.GetSaveAsFilename(POFilePath & POFileName, fileFilter:="XML files (*.xml),*.xml", Title:="Save FileAs...")
End If
If strFilePath = "False" Then Exit Sub
This gives me the right filename suggestion, but it doesn't direct me to the folder and goes to Desktop.
Any help would be appriciated!
EDIT:
I tried merging the Strings together a bit more and came up with this:
Public Sub ExportToXML()
Dim strFilePath As String
Dim POFilePath As String
Dim FOFilePath As String
Dim XMLDoc As MSXML2.DOMDocument
Dim xNode As MSXML2.IXMLDOMNode
Dim xAttribute As MSXML2.IXMLDOMAttribute
Dim xElement As MSXML2.IXMLDOMElement
Dim xElementRoot As MSXML2.IXMLDOMElement
Application.ScreenUpdating = False
MainSheetName = ActiveSheet.Name
POFilePath = "C:\Users\admin\Desktop\" & Range("A24") & Range("A24").value & "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
FOFilePath = "C:\Users\admin\Desktop\" & Range("D22") & " " & Range("A22") & "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
If Range("A24").value = "0" Then
strFilePath = Application.GetSaveAsFilename(FOFilePath, fileFilter:="XML files (*.xml),*.xml", Title:="Save FileAs...")
Else
strFilePath = Application.GetSaveAsFilename(POFilePath, fileFilter:="XML files (*.xml),*.xml", Title:="Save FileAs...")
End If
If strFilePath = "False" Then Exit Sub
The problem is, that VBA thinks that in:
POFilePath = "C:\Users\admin\Desktop\" & Range("A24") & Range("A24").value & "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
the first Range("A24") belongs to the filename part and doesn't continue on with the filepath. So if the value in A24 was "test", then this suggests saving the xml to Desktop with the filename testttest_report 11 2020
I have got an Excel-Code to generate singular word-mailmerged-documents.
It all work fine. The only problem is that after running the code and closing excel there is still one word instance running in the taskmanager.
Can someone help me fixing this?
My code so far is:
Private Sub CommandButton1_Click()
Dim wordApp As Word.Application
Dim wordTemplate As Word.Document
Dim wordMergedDoc As Word.MailMerge
Dim sourceBookPath As String
Dim sheetSourceName As String
Dim excelColumnFilter As String
Dim queryString As String
Dim baseQueryString As String
Dim wordTemplateDirectory As String
Dim wordTemplateFileName As String
Dim wordTemplateFullPath As String
Dim wordOutputDirectory As String
Dim wordOutputFileName As String
Dim wordOutputFullPath As String
Dim idListValues As Variant
Dim idValue As Integer
Dim idCounter As Integer
Dim recordCounter As Integer
Dim fileCounter As Integer
idListValues = Array(1, 2, 3, 4, 5, 6, 7)
sourceBookPath = ThisWorkbook.FullName
sheetSourceName = "Sheet1"
excelColumnFilter = "Anz"
baseQueryString = "SELECT * FROM `" & sheetSourceName & "$` where `" & excelColumnFilter & "` = [columFilterValue] order by `" & excelColumnFilter & "` ASC"
' Word:
wordTemplateDirectory = ThisWorkbook.Path & "\"
wordTemplateFileName = "sb[columFilterValue].docx"
wordOutputDirectory = ThisWorkbook.Path & "\"
wordOutputFileName = "MailMergeDifferent[columFilterValue]_[Record]"
Set wordApp = New Word.Application
wordApp.Visible = False
wordApp.DisplayAlerts = wdAlertsNone
MsgBox "Verteidigungsanzeigen werden erstellt, bitte kurz warten :)", vbOKOnly + vbInformation, "Information"
For idCounter = 0 To UBound(idListValues)
idValue = idListValues(idCounter)
queryString = Replace(baseQueryString, "[columFilterValue]", idValue)
wordTemplateFullPath = wordTemplateDirectory & Replace(wordTemplateFileName, "[columFilterValue]", idValue)
Set wordTemplate = wordApp.Documents.Open(wordTemplateFullPath)
Set wordMergedDoc = wordTemplate.MailMerge
With wordMergedDoc
.MainDocumentType = wdFormLetters
.OpenDataSource _
Name:=sourceBookPath, _
ReadOnly:=True, _
Format:=wdOpenFormatAuto, _
Revert:=False, _
AddToRecentFiles:=False, _
LinkToSource:=False, _
Connection:="Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;" & _
"Data Source=" & sourceBookPath & ";Mode=Read;Extended Properties=""HDR=YES;IMEX=1"";", _
SQLStatement:=queryString
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
For recordCounter = 1 To .DataSource.RecordCount
With .DataSource
.FirstRecord = wordMergedDoc.DataSource.ActiveRecord
.LastRecord = wordMergedDoc.DataSource.ActiveRecord
Dokumentenname = .DataFields("ID")
End With
.Execute Pause:=False
wordOutputFullPath = wordOutputDirectory & Replace(Replace(wordOutputFileName, "[columFilterValue]", idValue), "[Record]", recordCounter)
wordApp.ActiveDocument.SaveAs2 Filename:=wordOutputDirectory & Dokumentenname & ".docx", FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
wordApp.ActiveDocument.Close SaveChanges:=False
.DataSource.ActiveRecord = wdNextRecord
fileCounter = fileCounter + 1
Next recordCounter
End With
wordTemplate.Close False
Next idCounter
wordApp.Visible = False
Set wordApp = Nothing
MsgBox "Geschafft! Es wurden " & fileCounter & " Verteidigungsanzeigen erstellt", vbOKOnly + vbInformation, "Information"
End Sub
Try adding wordApp.Quit right before Set wordApp = Nothing
I count the number of emails in Outlook by Category.
I am getting the output in a MsgBox.
I want the output in Excel.
Example-
Category No of Emails
Material(blue) 42
Vendor(green) 5
Macro used as below
Sub CategoriesEmails()
Dim oFolder As MAPIFolder
Dim oDict As Object
Dim sStartDate As String
Dim sEndDate As String
Dim oItems As Outlook.Items
Dim sStr As String
Dim sMsg As String
On Error Resume Next
Set oFolder = Application.ActiveExplorer.CurrentFolder
Set oDict = CreateObject("Scripting.Dictionary")
sStartDate = Date - 365
sEndDate = Date
Set oItems = oFolder.Items.Restrict("[Received] >= '" & sStartDate & "' And [Received] <= '" & sEndDate & "'")
oItems.SetColumns ("Categories")
For Each aitem In oItems
sStr = aitem.Categories
If Not oDict.Exists(sStr) Then
oDict(sStr) = 0
End If
oDict(sStr) = CLng(oDict(sStr)) + 1
Next aitem
sMsg = ""
For Each aKey In oDict.Keys
sMsg = sMsg & aKey & ": " & oDict(aKey) & vbCrLf
Next
MsgBox sMsg
Set oFolder = Nothing
End Sub
Based on your code, I've updated my code, you can paste all and run it:
Sub CategoriesEmails()
Dim oFolder As MAPIFolder
Dim oDict As Object
Dim sStartDate As String
Dim sEndDate As String
Dim oItems As Outlook.Items
Dim sStr As String
Dim sMsg As String
Dim strFldr As String
Dim OutMail As Object
Dim xlApp As Object
On Error Resume Next
Set oFolder = Application.ActiveExplorer.CurrentFolder
Set oDict = CreateObject("Scripting.Dictionary")
sStartDate = Date - 365
sEndDate = Date
Set oItems = oFolder.Items.Restrict("[Received] >= '" & sStartDate & "' And [Received] <= '" & sEndDate & "'")
oItems.SetColumns ("Categories")
For Each aItem In oItems
sStr = aItem.Categories
If Not oDict.Exists(sStr) Then
oDict(sStr) = 0
End If
oDict(sStr) = CLng(oDict(sStr)) + 1
Next aItem
sMsg = ""
i = 0
strFldr = "D:\"
Set xlApp = CreateObject("Excel.Application")
xlApp.Application.Visible = True
xlApp.Workbooks.Open strFldr & "test.xlsx"
xlApp.Sheets("Sheet1").Select
For Each aKey In oDict.Keys
xlApp.Range("a1").Offset(i, 0).Value = sMsg & aKey
xlApp.Range("B1").Offset(i, 0).Value = oDict(aKey) & vbCrLf
i = i + 1
Next
xlApp.Save
Set oFolder = Nothing
End Sub
You could change the fileUrl, fileName, Excel field as your actual situation.
I want to clear a shared calendar.
I have a delete method that works in my Outlook calendar however it doesn't clear the shared calendar.
Private Sub DeleteAllAppointments()
Dim olkApp As Object, _
olkSession As Object, _
olkCalendar As Object, _
olkItem As Object, _
intIndex As Integer
Set olkApp = CreateObject("Outlook.Application")
Set olkSession = olkApp.Session
olkSession.Logon
Set olkCalendar = olkSession.GetDefaultFolder(olFolderCalendar)
For intIndex = olkCalendar.Items.Count To 1 Step -1
Set olkItem = olkCalendar.Items.Item(intIndex)
olkItem.Delete
Next
Set olkItem = Nothing
Set olkCalendar = Nothing
olkSession.Logoff
Set olkSession = Nothing
Set olkApp = Nothing
End Sub
This is where the method fails
Set olkCalendar = olkSession.GetDefaultFolder(olFolderCalendar)
Is this is a folder path issue?
This is how I did it.
Sub Delete_SharedCal_History()
DeleteCal_Appts "Office Calendar", "1/9/2001", "0:00:01", "12/31/2013", "23:59:59"
End Sub
Sub DeleteCal_Appts(sCalendarName As String, ap_dateStart As String, ap_startTime As String, ap_dateEnd As String, ap_endTime As String)
' Specified Shared Calendar - Delete all events in specified Date Range
' Author: Frank Zakikian
Dim objAppointment As AppointmentItem
Dim objAppointments As Items
Dim objNameSpace As NameSpace
Dim objRecip As Recipient
Dim nInc As Integer
Dim sFilter As Variant
Dim dtStartTime As Date, dtEndTime As Date
dtStartTime = CDate(ap_dateStart & " " & ap_timeStart)
dtEndTime = CDate(ap_dateEnd & " " & ap_timeEnd)
Set objNameSpace = Application.GetNamespace("MAPI")
'next line would be for use of personal calendar object..
'Set objAppointments = objNameSpace.GetDefaultFolder(olFolderCalendar)
Set objRecip = objNameSpace.CreateRecipient(sCalendarName)
objRecip.Resolve
'Debug.Print objRec.AddressEntry
Set objAppointments = objNameSpace.GetSharedDefaultFolder(objNameSpace.CreateRecipient("Akron Chambers Calendar"), olFolderCalendar).Items
sFilter = "[Start] > '" & Format(dtStartTime, "ddddd h:nn AMPM") & _
"' And [Start] < '" & Format(dtEndTime, "ddddd h:nn AMPM") & "'"
objAppointments.Sort "[Start]", False
Debug.Print "Total Items at begin: " & objAppointments.Count 'dev. fyi
Set objAppointment = objAppointments.Find(sFilter)
While TypeName(objAppointment) <> "Nothing"
'If MsgBox(objAppointment.Subject & vbCrLf & "Delete " & objRec.AddressEntry & " item now? ", vbYesNo, "Delete Calendar Item") = vbYes Then
objAppointment.Delete
nInc = nInc + 1
'End If
Set objAppointment = objAppointments.FindNext
Wend
MsgBox "Deleted " & nInc & " calendar items.", vbInformation, "Delete done"
Debug.Print "Total Items at finish: " & objAppointments.Count 'dev. fyi
Set objAppointment = Nothing
Set objAppointments = Nothing
End Sub
olkSession.GetDefaultFolder(olFolderCalendar) would retrieve your default Calendar folder. You need to either use olkSession.GetSharedDefaultFolder(someRecipient, olFolderCalendar) (where someRecipient is returned by olkSession.CreateRecipient) or open the appropriate store from the Namespace.Stores collection (assuming the delegate mailbox is already there) and call Store.GetDefaultFolder.