The below code extracts attachments from *.msg files stored in one folder.
I'm seeking to extract attachments from *.msg files stored in many subfolders within a folder.
The path for the main Folder is:
U:\XXXXX\XXXXX\Main Folder
The paths for the subfolders are:
U:\XXXXX\XXXXX\Main Folder\Folder1
U:\XXXXX\XXXXX\Main Folder\Folder2
U:\XXXXX\XXXXX\Main Folder\Folder3
etc.
Sub SaveOlAttachments()
Dim msg As Outlook.MailItem
Dim att As Outlook.Attachment
Dim strFilePath As String
Dim strAttPath As String
'path for msgs
strFilePath = "U:\XXXXX\XXXXX\Main Folder\"
'path for saving attachments
strAttPath = "D\Attachments\"
strFile = Dir(strFilePath & "*.msg")
Do While Len(strFile) > 0
Set msg = Application.CreateItemFromTemplate(strFilePath & strFile)
If msg.Attachments.Count > 0 Then
For Each att In msg.Attachments
att.SaveAsFile strAttPath & att.FileName
Next
End If
strFile = Dir
Loop
End Sub
Using my answer from VBA macro that search for file in multiple subfolders
Sub SaveOlAttachments()
Dim msg As Outlook.MailItem
Dim att As Outlook.Attachment
Dim strFilePath As String
Dim strAttPath As String
Dim colFiles As New Collection, f
'path for msgs
strFilePath = "U:\XXXXX\XXXXX\Main Folder\"
GetFiles strFilePath , "*.msg", True, colFiles
'path for saving attachments
strAttPath = "D\Attachments\"
For Each f in colFiles
Set msg = Application.CreateItemFromTemplate(f)
If msg.Attachments.Count > 0 Then
For Each att In msg.Attachments
att.SaveAsFile strAttPath & att.FileName
Next
End If
Next
End Sub
Sub to perform the search:
Sub GetFiles(StartFolder As String, Pattern As String, _
DoSubfolders As Boolean, ByRef colFiles As Collection)
Dim f As String, sf As String, subF As New Collection, s
If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
f = Dir(StartFolder & Pattern)
Do While Len(f) > 0
colFiles.Add StartFolder & f
f = Dir()
Loop
sf = Dir(StartFolder, vbDirectory)
Do While Len(sf) > 0
If sf <> "." And sf <> ".." Then
If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
subF.Add StartFolder & sf
End If
End If
sf = Dir()
Loop
For Each s In subF
GetFiles CStr(s), Pattern, True, colFiles
Next s
End Sub
Related
I am creating a new database for where I work. It is creating quotes for jobs. When I click the save button its save the quote and opens a new folder which gets its name from three fields on the form. I want it to import or copy files from another folder in the directory to the newly created folder.
I have tried to use the copyfolder function and it does copy the files but to the main folder where all the quotes are held and not into the newly created folder.
On Error GoTo btnOK_Click_Error
Const strParent = "C:\Users\r.jones\Desktop\Quotes\ "
Dim Strquotenumber As String
Dim Strsite As String
Dim StrprojDesc As String
Dim strFolder As String
Dim Strspace As String
Strspace = Space(1) & "- "
Strquotenumber = Me.QuoteNumber
Strsite = Me.Txtsite
StrprojDesc = Me.Project_Description
strFolder = strParent & Strquotenumber & Strspace & Strsite & Strspace & StrprojDesc
If Dir(strFolder, vbDirectory) = "" Then MkDir strFolder
Shell "explorer.exe " & strFolder, vbNormalFocus
If Me.Dirty Then DoCmd.RunCommand acCmdSaveRecord
DoCmd.Close acForm, Me.Name
DoCmd.OpenForm "Frmquotebook"
btnOK_Click_Exit:
Exit Sub
btnOK_Click_Error:
MsgBox "Error" & " In Attempting To Create New Folder. All Fields Must Be Filled In." & vbCrLf_
Cancel = True
Resume btnOK_Click_Exit
Is it possible to do this as I have not been able to find anything on it.
Thanks for the help.
Here are some file system routines I use, wrapping the Scripting.FileSystemObject Object:
Public Function FileExists(FileName As String) As Boolean
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
FileExists = fso.FileExists(FileName)
End Function
Public Sub DeleteFile(FileName As String)
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If FileExists(FileName) Then fso.DeleteFile FileName, True
End Sub
Public Sub CopyFile(Source As String, Destination As String, Optional force As Boolean = False)
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If FileExists(Source) Then
fso.CopyFile Source, Destination, force
End If
End Sub
Public Sub CreateFolder(Folder As String)
Dim fso As Object
Dim Position As Integer
Dim TempFolder As String
Dim Folders As Object
Dim strArr() As String
Dim i As Integer
Position = 0
TempFolder = ""
strArr = Split(Folder, "\")
Set fso = CreateObject("Scripting.FileSystemObject")
For i = 0 To UBound(strArr)
If Not fso.FolderExists(TempFolder & strArr(i) & "\") Then
Set Folders = fso.GetFolder(TempFolder).subFolders
Folders.Add (strArr(i))
End If
TempFolder = TempFolder & strArr(i) & "\"
Next
End Sub
You will need to iterate over each file in the source directory and cop it over to the destination directory
Sub CopyFilesInDirectoryToFolder(SourceDirectory As String, DestinationDirectory As String)
Dim fileName As String
If Not Right(SourceDirectory, 1) = Application.PathSeparator Then SourceDirectory = SourceDirectory & Application.PathSeparator
If Not Right(DestinationDirectory, 1) = Application.PathSeparator Then DestinationDirectory = DestinationDirectory & Application.PathSeparator
fileName = Dir(SourceDirectory)
Do While Len(fileName) > 0
CopyFile SourceDirectory & fileName, DestinationDirectory & fileName
fileName = Dir()
Loop
End Sub
I have a folder of ~20 *.potx files and I would like to convert all *.potx files to *.pptx, then delete the *.potx files.
The following will loop through all your templates, convert, and delete the template files.
Sub loopFiles()
Dim fso As New FileSystemObject
Dim fil As File
Dim fold As Folder
Set fold = fso.GetFolder(yourFolder)
For Each fil In fold.Files
If InStr(1, fil.Name, ".potx") > 0 Then
Application.Presentations.Open fil.Path
ActivePresentation.SaveAs Replace(fil.Path, ".potx", ".pptx"), ppSaveAsDefault
ActivePresentation.Close
'if you truly want to delete them, don't recommend since they are .potx
fil.Delete True
End If
Next fil
End Sub
You could try something like this: (replace YOUR FOLDER HERE with your folder name)
Public Sub ConvertPP()
Dim pApp As Object
Set pApp = CreateObject("Powerpoint.Application")
Dim sFile As String
Dim sFolder As String
sFolder = "YOUR FOLDER HERE"
sFile = Dir(sFolder & "\*.potx")
Do Until sFolder = ""
pApp.Presentations.Open sFolder & "\" & sFile
pApp.ActivePresentation.SaveAs sFolder & "\" & Replace(sFile, "potx", "pptx"), 11
pApp.ActivePresentation.Close
sFile = Dir()
Loop
pApp.Quit
Set pApp = Nothing
End Sub
I created a code to export my files from outlook and send them to a folder (excluding the signatures). My new challenge is to make sure that when a file is downloaded, if a file with the same name already exists in the folder then it should not run the code.
I have thought of using such a code but have tried unsuccessfully to integrate it in my code at the bottom of this post:
Dim TestStr As String
On Error Resume Next
TestStr = Dir(FilePath)
On Error GoTo 0
If TestStr = "" Then
FileExist = False
Else
FileExist = True
End If
End Function
Here is my unsuccessful code so far which I can't seem to debug:
Public Sub Samenamesameformat(Item As Outlook.MailItem)
Dim Atmt As Outlook.Attachment
Dim SavePath As String
Dim objFSO As Object
Dim sExt As String
Dim TestStr As String
SavePath = "C:\Users\Antoine.moyroud\Documents\Testexportadwords"
On Error Resume Next
TestStr = Dir(SavePath)
On Error GoTo 0
If TestStr = "" Then
FileExist = False
Else
FileExist = True
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each Atmt In Item.Attachments
sExt = objFSO.GetExtensionName(Atmt)
Select Case sExt
Case "jpg", "png"
Case Else
Atmt.SaveAsFile SavePath & "\" & Atmt.DisplayName
End Select
End If
Next
Set Atmt = Nothing
End Sub
Thanks!
try this
Public Sub Samenamesameformat(Item As MailItem)
Dim Atmt As Attachment
Dim SavePath As String
Dim objFSO As Object
Dim sExt As String
SavePath = "C:\Users\Antoine.moyroud\Documents\Testexportadwords"
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each Atmt In Item.Attachments
If Not objFSO.FileExists(SavePath & "\" & Atmt.FileName) Then
sExt = objFSO.GetExtensionName(Atmt)
Select Case sExt
Case "jpg", "png"
Case Else
Atmt.SaveAsFile SavePath & "\" & Atmt.DisplayName
End Select
End If
Next
End Sub
I'm assuming your sub runs from inside Outlook, so that you don't need that .Outlook prefix for all Outlook Application Object Model variables
Sub ReplaceEntireHdr()
Dim wrd As Word.Application
Set wrd = CreateObject("word.application")
wrd.Visible = True
AppActivate wrd.Name
'Change the directory to YOUR folder's path
fName = Dir("C:\Users\user1\Desktop\A\*.doc")
Do While (fName <> "")
With wrd
'Change the directory to YOUR folder's path
.Documents.Open ("C:\Users\user1\Desktop\A\" & fName)
If .ActiveWindow.View.SplitSpecial = wdPaneNone Then
.ActiveWindow.ActivePane.View.Type = wdPrintView
Else
.ActiveWindow.View.Type = wdPrintView
End If
.ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
.Selection.WholeStory
.Selection.Paste
.ActiveDocument.Save
.ActiveDocument.Close
End With
fName = Dir
Loop
Set wrd = Nothing
End Sub
I use this vba code to replace all the headers, of all the word documents in a folder 'A'. However if there is any subfolder in the parent folder 'A' with word documents, the vba code skips those documents. Could anyone please tell me how to include the word documents in the subfolders as well? Perhaps by making some changes in the code or any other vba code which can do the same job.
Thanks in advance.
In order to pick up the folders (directories) you need to specify the vbDirectory attribute. By default, Dir only "sees" things that match vbNormal.
Here's an example that picks up both files and sub-directories. The GetAttr function checks whether the file attribute is vbDirectory. If it's not, then it's a file.
What you can do is save the directory paths in an array, then loop that to get the files in the sub-directories.
Sub GetFilesandSubDir()
Dim sPath As String, sPattern As String
Dim sSearch As String, sFile As String
Dim sPathSub As String, sSearchSub As String
Dim aSubDirs As Variant, i As Long
sPattern = "*.*"
sPath = "C:\Test\"
sSearch = sPath & sPattern
sFile = Dir(sPath, vbNormal + vbDirectory)
aSubDirs = TestDirWithSubFolders(sPath, sPattern, sSearch, sFile)
For i = LBound(aSubDirs) To UBound(aSubDirs)
Debug.Print "Directory: " & aSubDirs(i)
sPathSub = sPath & aSubDirs(i) & "\"
sSearchSub = sPathSub & sPattern
sFile = Dir(sPathSub, vbNormal + vbDirectory)
TestDirWithSubFolders sPathSub, sPattern, sSearchSub, sFile
Next
End Sub
Function TestDirWithSubFolders(sPath As String, sPattern As String, _
sSearch As String, sFile As String) As Variant
Dim aSubDirs() As Variant, i As Long
i = 0
Do While sFile <> ""
If GetAttr(sPath & sFile) = vbDirectory Then
'Debug.Print "Directory: " & sFile
ReDim Preserve aSubDirs(i)
aSubDirs(i) = sFile
i = i + 1
Else
Debug.Print "File: " & sFile
End If
sFile = Dir
Loop
TestDirWithSubFolders = aSubDirs
End Function
Here's my code:
Sub isdofsodjisf48023jroi23f984444444jiodfiosj12348023jroi23f98()
Dim colFiles As New Collection
RecursiveDir colFiles, "C:\Documents and Settings\Alex Gordon\Desktop\testing\files\", "*.xls", True
Dim vFile As Variant
For Each vFile In colFiles
Call writeincells(vFile)
Next vFile
End Sub
Public Function RecursiveDir(colFiles As Collection, _
strFolder As String, _
strFileSpec As String, _
bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
'Add files in strFolder matching strFileSpec to colFiles
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
colFiles.Add strFolder & strTemp
strTemp = Dir
Loop
If bIncludeSubfolders Then
'Fill colFolders with list of subdirectories of strFolder
strTemp = Dir(strFolder, vbDirectory)
Do While strTemp <> vbNullString
If (strTemp <> ".") And (strTemp <> "..") Then
If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
colFolders.Add strTemp
End If
End If
strTemp = Dir
Loop
'Call RecursiveDir for each subfolder in colFolders
For Each vFolderName In colFolders
Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
Next vFolderName
End If
End Function
Public Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
If Right(strFolder, 1) = "\" Then
TrailingSlash = strFolder
Else
TrailingSlash = strFolder & "\"
End If
End If
End Function
I am filling up a Collection with a list of filenames in a directory structure.
I have 2000 files, but the Collection only return 256. Does anyone know if there is a maximum number that it won't go past?
If so, can you please suggest a better way to code this macro so that it captures all 2000 files?
The code is working OK in Excel 2007. Perhaps what is happening is that you are trying to Watch the Collection in Debug mode. The Debugger shows only the first 256 items.
How about a disconnected recordset? This thread is about VBScript, but it is very similar to VBA:
How do I sort arrays using vbscript?