I have a vba syntax which search for only pdf files.I wanted to know what changes do I need to make in the below code so that it can search docx and similar ext files as well.
If pfile <> "" And Right(pfile, 3) = "pdf" Then
Set obMail = Outlook.CreateItem(olMailItem)
First change your Dir command to look for folder & "\*.*. While you've neglected to incude that important postion of your code, a Dir list isn't going to return anything that is outside of its file mask. Next, pull the file extension off the right hand end and compare it to a list of desired file extensions.
dim folder as string, pfile as string, ext as string
folder = "c:\temp"
pfile = Dir(folder & "\*.*")
do while cbool(len(pfile))
ext = chr(32) & lcase(trim(right(replace(pfile, chr(46), space(99)), 99))) & chr(32)
if cbool(instr(1, " pdf docx doc xls xlsx ", ext, vbTextCompare)) then
'do something with the matching file
end if
pfile = Dir
loop
Related
Hey I have a code where I want to find .jpg file in different folders so my code looks like this :
file = Dir(folder & "\*.jpg")
But it turns out there are also .png file in these folders, is there an easy and simple way to make it so that the Dir() also find png images ? Maybe using regular expression somehow or even an even more simple way I didn't think of ? I know there are a lots of way, but I'd like it if I don't have to change all my code... Thanks for anyone answering :)
Please, try the next way:
Dim file as string, folder as string, arrExt
folder = "your folder path"
file = Dir(folder & "\*.*")
Do While file <> ""
arrExt = split(file, ".")
If UCase(arrExt(Ubound(arrExt))) = "JPG" Or _
UCase(arrExt(Ubound(arrExt))) = = "PNG" Then
' do whatever you need
End If
file = Dir
Loop
Use Dir(folder & "\*.*") to list all files and check by hand if it is a file you are interested in, eg with a function like this:
Function isImage(fileName As String) As Boolean
Dim ext As String, p As Long
p = InStrRev(fileName, ".")
If p = 0 Then Exit Function
ext = LCase(Mid(fileName, p + 1))
isImage = (ext = "jpg" Or ext = "jpeg" Or ext = "png")
End Function
I have Excel VBA code that sends data to a word template (saves a docx and pdf file).
The code then sends the pdf as an email via outlook.
It all works perfectly on my local drive, but opening, checking and saving folders and files to sharepoint has beaten me. I've spent hours searching and experimenting....there seems to be some conflicting ports (mainly on other forums).
Surely I'm not alone here....
Code that works on my local drive is:
thefilepath = Application.ActiveWorkbook.Path
Set wrdDoc = wrdApp.Documents.Open(thefilepath & "\Letter Template.docx", ReadOnly:=True)
strFolderPath = thefilepath & "\Results"
CheckDir (strFolderPath)
<Run code>
wrdDoc.SaveAs thefilepath & "\Results\" & thefilename & ".doc"
wrdDoc.ExportAsFixedFormat OutputFileName:=thefilepath & "\Results\" & thefilename & ".pdf", ExportFormat:=wdExportFormatPDF
Function CheckDir(Path As String)
If Dir(Path, vbDirectory) = "" Then
MkDir (Path)
End If
End Function
Problems…
Thefilepath is not accurate…..returns “C:\Users\sf\PP\WIP\a Macros”
I’m struggling to create the “results” subfolder
Docx and PDF naming is giving me errors.
My excel file is in
thisdir = https://pplanners.sharepoint.com/sites/PP/Shared Documents/PP WIP/a Macros
I want to save my docx and pdf files to thisdir & "/results" Ie.
resultsdir = https://pplanners.sharepoint.com/sites/PP/Shared Documents/PP WIP/a Macros/results
So to test if the results subdirectory exists I've tried....
If Dir("/pplanners.sharepoint.com/sites/PP/Shared%20Documents/PP%20WIP/a%20Macros/results", vbDirectory) = "" Then
If Dir("//pplanners.sharepoint.com/sites/PP/Shared%20Documents/PP%20WIP/a%20Macros/results", vbDirectory) = "" Then
If Dir("https://pplanners.sharepoint.com/sites/PP/Shared%20Documents/PP%20WIP/a%20Macros/results", vbDirectory) = "" Then
But nothing seems to work
Similarly, for MkDir, I’ve tried
MkDir "https://pplanners.sharepoint.com/sites/PP/Shared%20Documents/PP%20WIP/a%20Macros/Results"
MkDir "//pplanners.sharepoint.com/sites/PP/Shared%20Documents/PP%20WIP/a%20Macros/Results"
MkDir "/pplanners.sharepoint.com/sites/PP/Shared%20Documents/PP%20WIP/a%20Macros/Results"
MkDir "https://pplanners.sharepoint.com/sites/PP/Shared%20Documents/PP%20WIP/a%20Macros/Results"
MkDir "//pplanners.sharepoint.com/sites/PP/Shared%20Documents/PP%20WIP/a%20Macros/Results"
MkDir "/pplanners.sharepoint.com/sites/PP/Shared%20Documents/PP%20WIP/a%20Macros/Results"
Handy code that I’ve used to tweak name so far is:
tr = ThisWorkbook.Path
tr2 = Replace(Replace(tr, "http:", ""), "/", "\")
tr3 = Replace(tr2, " ", "%20")
Hoping to get some discussion going on file and folder management with sharepoint.
I'm using code to open all the files in a folder that start with a particular prefix:
folder = "C:\Users\xxx\Documents\Exception Reports\"
pref = "blah blah prefix"
file = pref & "*.xls"
exPath = folder & file
filename = Dir(exPath)
Do While filename <> ""
Workbooks.Open (filename)
...
Workbooks(filename).Close SaveChanges:=False
filename = Dir()
Loop
The first time I run the code after opening the macro, I get "Sorry we couldn't find -filename-. Is it possible it was moved, renamed, or deleted?" But the -filename- it prints is the one I want it to open, and all I have specified is the prefix I want and the file extension, so it would seem to me like it's finding it just fine if it knows the full file name. Also if I put in a message box between declaring the filename variable and starting the Do While loop, the message box prints the correct filename that I want it to open.
If I save a new file into the folder and name it something like "AA.xls", and then just have the program loop through the folder (rather than specifying the prefix), and then go back and specify the prefix, it works just fine, and continues to work until I close the program and reopen, where the process starts all over. However, this process only works if I save a new file to that folder. If I try to leave the "AA.xls" file in the folder, I get the same error with that file that I get with the others.
Thanks for any input!
Try using a CMD approach and see if you get the same problem, if you do then it's more than likely a permissions issue:
Sub SO()
Const folder As String = "C:\Users\xxx\Documents\Exception Reports\"
Const pref As String = "blah blah prefix"
Dim file As String
Dim exPath As String
Dim fileName As Variant
file = pref & "*.xls": exPath = folder & file
For Each fileName In _
Filter(Split(CreateObject("WScript.Shell").Exec("CMD /C DIR """ & exPath & """ /B /A:-D").StdOut.ReadAll, vbCrLf), ".")
Workbooks.Open CStr(folder & fileName)
'// Do code here
Workbooks(fileName).Close False
Next fileName
End Sub
I download reports on a daily/weekly basis but when downloading the system auto generates the file name with a date at the end although the basic file name is the same. ie ANAPOS - 20141001. I'm using a simple open command (Workbooks.OpenText Filename:="C:\Users\903270\Documents\Excel\ANAPOS.txt") to do some other stuff but before doing so I need to rename the file to ANAPOS.txt before I can run it.
Is there any code that will allow my macro to search for ANAPOS with out all the other info at the end?
Any help appreciated.
Set filePath to where you want to search
Sub getANAPOS()
Dim Filter As String, filePath As String
filePath = "C:\Data\VBA\SO\"
Filter = "ANAPOS files (*.txt), filepath & ANAPOS*.txt"
ANAPOSSelectedFile = Application.GetOpenFilename(Filter)
End Sub
EDIT FOLLOWING CLARIFICATION BY OP
Sticking with the same theme, this should give you some scope to work with. It essentially 'automatically' renames the selected file in situ, unless it already exists. Acknowledgements to #Gary's Student for his neat ideas to parse the GetOpenFileName result, here.
Sub renameANAPOS()
Dim Filter As String, filePath As String, newName As String
'filter txt file names containing 'ANAPOS'
Filter = "ANAPOS files (*.txt), filepath & ANAPOS*.txt"
'the 'rename' name
newfName = "ANAPOS"
'navigate to original ANAPOS file and location details
ANAPOSSelectedFile = Application.GetOpenFilename(Filter)
'parse selected file details
fullArr = Split(ANAPOSSelectedFile, "\")
detArr = Split(fullArr(UBound(fullArr)), ".")
fullArr(UBound(fullArr)) = ""
fPath = Join(fullArr, "\")
fName = detArr(0)
fExt = detArr(1)
'rename file in not already exixts
If Len(Dir(fPath & newfName & "." & fExt)) > 0 Then
MsgBox newfName & "." & fExt & " already exists in this folder."
Exit Sub
Else
Name ANAPOSSelectedFile As fPath & newfName & "." & fExt
End If
End Sub
So basically the intent is the use a VBA dir function in a directory, get the file names in that directory, but avoid/filter out getting a certain extension. e.g., I'd like to get all the files in a directory that aren't "*.txt" or whatever. I would strongly prefer to use the dir function as opposed to some other solution, as it seems to be exceedingly more efficient/quick at getting file lists vs anything else I've tried.
For example, something like Dir("Path" & "" & <> ".txt"). But you know... something that works. haha.
I could certainly just have a check after the fact to skip over anything with a .txt extension (split a string or whatever), but I was wondering if there was something more elegant/resource efficient that I could use with the syntax of a Dir function to avoid files of a certain extension.
Thanks in advance!
Dim Files As Collection
Set Files = GetFilesIn("C:\") 'gets all the files
Set Files = GetFilesIn("C:\", "*.txt") 'gets all the txt files
Set Files = GetFilesIn("C:\", , "*.txt") 'gets all but the txt files
Function GetFilesIn(Folder As String, Optional Matching As String, Optional Unmatching As String) As Collection
Dim FName As String
Set GetFilesIn = New Collection
If Matching = "" Then
FName = Dir(Folder)
Else
FName = Dir(Folder & Matching)
End If
Do While FName <> ""
If Unmatching = "" Then
GetFilesIn.Add Folder & FName
Else
If Not FName Like Unmatching Then GetFilesIn.Add Folder & FName
End If
FName = Dir
Loop
End Function