Len() as argument for Dir() - excel

So I am looping through a folder and have set a few arguments to filter the loop. I am trying to do so for file length as well but I am getting a run time error 13 type mismatch. Guessing there's no way to use file length as an argument for Dir()? What's a good workaround?
path = subF & "\"
extension = "*.xlsm"
partialName = "C*"
file = Dir(path & partialName & Len(file) = 13 & extension) '<- error
I can do
length = Len(file)
If length = 13 Then
inside the loop but without going into details, I need to do so outside of the loop.
Neither this or this is helping. And SO seems to only discuss file length with python not excel :/

You want filenames that are a total of 13 characters long to include a period and a four letter file extension, so you really want filenames that are 8 characters long and starts with a C. The file mask you are currently using involved the asterisk which is the wildcard character for any number of characters. Switch to seven (7) question marks after the C and you should be filtering your Dir function for file names that are eight characters long starting with a C with an .xlsm file extension.
path = subF & "\"
extension = ".xlsm"
partialName = "C???????"
file = Dir(path & partialName & extension) '\C???????.xlsm

Remove the * wildcards and use the '?' wildcard instead:
path = subF & "\"
partialName = "C"
extension = ".xlsm"
file = Dir(path & partialName & String(7, "?") & extension)
If you want 13 char between "C" and ".xlsm" use string(13, "?") instead.
Edit in response to comment:
Minimizing variables -
path = subF & "\C" & String(7, "?") & ".xlsm"
file = Dir(path)
or
file = Dir(subF & "\C???????.xlsm")

Related

Using Wildcard For Folder In The Mid Of The Path

So I have folder series like "ABC1000, ABD2000, ABE3000,...". With the input I have I need to copy a file from these. The information I have last 4 digit (numbers), these are unique per folder but since I do not know first 3 digits(letters) I need to use wildcard for letters. However I could not make it. And also I know that these all folder starts with "A".
While i <= lastRowTC
pathPD = Dir(pathSource & "\ABB\A*", vbDirectory) & ThisWorkbook.Worksheets("Add Dummy").Cells(i, 22).Value & "\getthisfile.xlsm"
FSO.CopyFile pathPD, pathWE
i = i + 1
Wend
Something more like this maybe:
Dim folderDigits, wsAdd As Worksheet
Set wsAdd = ThisWorkbook.Worksheets("Add Dummy")
While i <= lastRowTC
folderDigits = wsAdd.Cells(i, 22).Value
pathPD = Dir(pathSource & "\ABB\A??" & folderDigits, vbDirectory) & "\getthisfile.xlsm"
FSO.CopyFile pathSource & "\" pathPD, pathWE
i = i + 1
Wend
...if the name of the folder you're looking for is "A" followed by two other characters and then folderDigits

Using SaveAs Function, but periods change the fileformat

I open an Excel file, fill some cells and then save it in a new folder.
The generated files include today's date that includes periods.
If the filename for example is "Template_Name_01.01.2022" the fileformat changes to .2022
Dim OriginalFileName As String
fileName = "Template_" & Nz(rs!Street, "Address") & "_" & Date
OriginalFileName = fileName
Dim fileNumber As Integer
fileNumber = 1
Do Until nameFree = True
nameCheck = Dir("G:\Argus\_Deal Tracker 3.0\Deals_Inv Mgmt\" & fileName)
If nameCheck = "" Then
xlBook.SaveAs fileName:="G:\Argus\_Deal Tracker 3.0\Deals_Inv Mgmt\" & fileName, FileFormat:=xlOpenXMLStrictWorkbook
nameFree = True
Else
fileName = OriginalFileName
fileName = fileName & " (" & fileNumber & ")"
fileNumber = fileNumber + 1
End If
Loop
Even though I determine the fileFormat it saves the file as .2022
Saved files
If I add an ".xlsx" extension to the filename it works for me but not on other PCs, I am guessing it is because they have file extensions hidden.
If they run the function they get this error.
Is there a way to prevent the file format changing if periods appear in the name?
You need to format the Date to remove the forward slashes / from the file name as they're not allowed. You also need to supply the file extension in the path.
So, change this:
fileName = "Template_" & Nz(rs!Street, "Address") & "_" & Date
to this:
fileName = "Template_" & Nz(rs!Street, "Address") & "_" & Format(Date, "dd.mm.yyyy") & ".xlsx" 'change to your extension
Performing the Save As from script, you have to contruct the whole filename, including the extension.
Basically you have to add something like:
fileName = "Template_" & Nz(rs!Street, "Address") & "_" & Date & ".csv"

Excel vba - Dir(Path & File) not returning all matching files

I have a strange conundrum, a DIR() command returns files as expected except for a few cases.
MyFile = Dir(FilePath & FileLook)
FileFound = ""
FileKt = 0
Do While MyFile <> ""
FileFound = MyFile
FileKt = FileKt + 1
MyFile = Dir
Loop
FilePath = the directory where the files reside
(eg: C:\Folder\ )
FileLook = the template looking for a specific file which normally has HHMM after YYYYMMDD
(eg: ERROR_FILE_20201129*)
An exception that doesn't work is a file with no extension (.txt; .zip; etc) and "." separators in the name
XXXXXX.XXX.PROJ.EVENT_YYYYMMDD
An example of a search that returned a file (the majority):
FileLook = ERROR_FILE_20201029*
returned ERROR_FILE_202010291112.txt
Note: For the exception I tried the search with and without an "*"
To find just ERROR_FILE_202011291112.txt, you can use
FileLook = 'ERROR_FILE_20201129*.*'
But any "."s ahead of the "*" seem to invalidate the filter.
Admittedly a work-around, but you can also find all the files in the directory, by letting FileLook = "" and apply a filter external to the Dir command.
MyFile = Dir(FilePath)
FileFound = ""
FileKt = 0
Do While MyFile <> ""
If MyFile Like FileLook Then
FileFound = MyFile
FileKt = FileKt + 1
End If
MyFile = Dir
Loop
The following file names were in the folder I tested this against.
ERROR_FILE_2020.11.29.1112
ERROR_FILE_2020.11.29.1112.txt
ERROR_FILE_202011291112.txt
All three files were evaluated using FileLook = ""
Hope that works for you.
Thank you BZngr! You did point me to a workaround.
The original
MyFile = Dir(FilePath & FileLook)
was kept. I discovered on repeated testing that no file was found by the Dir() statement when there were just numbers at a certain point.
PROJ.EVENT_20201030* Returned ""
PROJ.EVENT_2020* Returned ""
PROJ.EVENT_202* Returned ""
PROJ.EVENT_20* Returned "PROJ.EVENT_202010301421"
As to why? ♪Twilight Zone music♪
There's years of files in the folder, so that's why I wanted to restrict the looping through unwanted files. At least this way I can limit to the current century.

How do I format a number to have at least 5 digits in a file name with a macro?

I'm working on a macro which involves generating a filename and saving an excel sheet as pdf with that name.
I was able to generate target folder name as follows.
user_name = Environ$("UserName")
file_dir = "C:\Users\" & user_name & "\Documents\Jobs\"
The file name is created as follows.
Job_No = Site & "SV" & num_from_cell
PDF = Job_No & ".pdf"
file_path = file_dir & PDF
Currently the above code returns MWSV234.pdf. I want it to be MWSV00234.pdf. num_from_cell comes from one of the cells in Excel sheet.
In short, I want to left pad num_from_cell to 5 digits. Could you please tell me how?
It would be safer to use Environ$("HomePath") to get the users home directory rather than Environ$("UserName")
file_dir = Environ$("HomePath") & "\Documents\Jobs\"
Then use Format to format with leading zeros for 5 numbers
Job_No = Site & "SV" & Format(num_from_cell, "00000")
PDF = Job_No & ".pdf"
file_path = file_dir & PDF

VBA comparing files before moving to another folder

I have been trying to use a code that ensures that there is a match from the input and output folders before moving input files into another folder. Here is a snippet:
'Select first Excel file within that Outlook_ImportedClaimsFiles folder path
OutlookImportFN = Dir(OutlookImportPath & "\*.xls")
'Select first Excel file within the SAS_Outputs folder path
SASOutputFN = Dir(SASOutputsPath & "\*.xls")
'Cycle through all files in the source folder path until there are no more left to cycle through
Do While OutlookImportFN <> ""
Counter = Counter + 1
'Create full path name of the source file
sFilePathName = OutlookImportPath & "\" & OutlookImportFN
'Create full path name of the destination file and add the date and time the file was moved
dFilePathName = OutlookRunPath & "\" & Format(Now, "yyyymmdd") & "_" & OutlookImportFN
The problem is that in the first folder (OutlookImportFN), there is a batch/holding file that contains the filenames for all the files in that folder that is used in the overall process. When flagging the first file, this file comes up first (this file shouldn't be flagged/selected at all). Because of this, when doing the comparison, the files don't match (unless I start with the 2nd file in the list). How do I either start with the 2nd file in the Input folder when comparing to the 1st file in the Output folder, or skip over this holding file in the Input folder when doing the comparison? I've tried a few things but nothing seems to work. Thanks in advance for your insight!
You need to add an If statement which makes sure the file isn't that batch file:
Do While OutlookImportFN <> ""
Counter = Counter + 1
If Not OutlookImportFN = "MyBatchFile" Then
'Create full path name of the source file
sFilePathName = OutlookImportPath & "\" & OutlookImportFN
'Create full path name of the destination file and add the date and time the file was moved
dFilePathName = OutlookRunPath & "\" & Format(Now, "yyyymmdd") & "_" & OutlookImportFN
End If

Resources