Dir function does not find a file, even after copy pasting the path as a parameter - vba

I've tried to get the Dir() function to work some time now using a rather complicated concatenated string, as seen below:
Dim Path as String
Path = Dir("PathToSubfolder\" & Year(Date) & "\" & MonthName(Month(Date)) & _
"\Production " & MonthName(Month(Date)) & "*.xlsx")
MsgBox Path
The message box prints nothing (it's just a blank Message Box). After trying to figure out whether I had mistyped the Path somehow, I opened up the correct file, and copypasted its actual Path from options, and subsequently performed: Path = Dir("PathToSubFolder\2016\June\Production June 2016.xlsx"), i.e. without any concatenation or anything, simply just the actual filepath and -name. However, Printing MsgBox Path returned nothing (NULL) again.
Does anyone have any clue as to why this wont work? I have used Dir quite extensively the last days from the same workbook (albeit not from the same module) without any issues.
Edit: Finally found a workaround. I simply made a variable with the path to the file, pathtoFile, and subsequently:
Dim pathtoFile As String
pathtoFile = "C:\Path.to.file\"
Path = Dir(pathtoFile & "*" & MonthName(Month(Date)) & "*")

Month(Date)
Will return a number, not a name. So you are passing the following argument:
PathToSubFolder\2016\6\Production 6 2016.xlsx
Which doesn't exist, hence you get a null string returned.
Try
Dim Path as String
Path = Dir("PathToSubfolder\" & Year(Date) & "\" & MonthName(Month(Date)) & _
"\Production " & MonthName(Month(Date)) & "*.xlsx")
MsgBox Path
the MonthName() method takes a number between 1 - 12 and returns the name of that month, which is what you need for your string.

Related

VB.NET Find if file with unknown elements exist?

I need to write an if function that finds if the a specific file exists, but the directory of the file contains unknown elements that may change from occasion to occasion. The code I have so far is:
If Dir(ProjectsFolder & ComboBox_ProjectType.Text & "\" & ProjectNumber & "\" & ProjectNumber & "_Rokasgramata\", ProjectNumber & "*User Manual*.pdf")(0) = "" Then
It returns an error and it's probably because of "*" What am I doing wrong? Could someone, please, help me with this one?
When working with paths use IO.Path.Combine
Use that path to create a New IO.DirectoryInfo(path)
This object has .Exists property to ensure that the directory exists.
Finally use .EnumerateFiles(ProjectNumber & "*User Manual*.pdf").Any() To check if any such file exists.
I was very close and figured it out on my own
If Dir(ProjectsFolder & ComboBox_ProjectType.Text & "\" & ProjectNumber & "\" & ProjectNumber & "_Rokasgramata\" & ProjectNumber & "*User Manual*.pdf") = "" Then

File not found - error 53 when trying to rename file that exists

Very weird as this code was running last night!!
I haven't changed anything and now it is failing as an error 53 - file not found.
Dim oldFilePath As String
Dim newFilePath As String
FolderPath = "C:\Users\ME\Documents\Scans\"
NewFileName = "Invoice " & InvID & " For " & LName & ", " & FName & ", " & ClaimNo
oldFilePath = FolderPath & Filename
newFilePath = FolderPath & NewFileName & ".pdf"
Debug.Print oldFilePath
Name oldFilePath As newFilePath <--FAIL HERE
The debugs are coming out:
C:\Users\ME\Documents\Scans\ZephyrClaims20181018161309042577.pdf
Which is correct.
This file exists and when I copy the debug code into a windows explorer address bar and press enter, then file opens in acrobat!
As mentioned this was working before.
This is a function which cycles through specific files in a folder, renames them and then loops.
The list of files are filenames only in an access DB, and then you can see the folder path there, which does have the "\" on the end.
Totally stuck if anyone has an idea!
I ahve also tried DIM as Variant, which had no effect.
I find it just so weird that this has worked for about 20 files and now is failing.
The error was caused by the NEW file name having illegal characters in it as per user #Andre comment!!!

Copy file and name it a value from the active cell

I need this code to copy the Word file and call it a value from the active cell
FileCopy Application.ThisWorkbook.path & "\template.docx", Application.ThisWorkbook.path & "\exercies\ & Worksheets(1).ActiveCell.Value & "".docx"
But it gives me an error "Bad file of number".
Can someone help me?
The problem is this part of your code:
"\exercies\ & Worksheets(1).ActiveCell.Value & "".docx"
If you Debug.Print this part of the statement, you'll get:
\exercies\ & Worksheets(1).ActiveCell.Value & ".docx
which is not a valid path.
Try replacing it with this instead:
"\exercies\" & ActiveCell.Value & ".docx"
which will produce a valid path. Furthermore, I suspect you have misspelled the folder name. Shouldn't it be exercises instead?

Trying to add an attachment to an email from excel where only the first part of the file name is known

I have a macro which I am using to attach an automatically generated file to an email on a daily basis.
The filename is required to be a certain format which includes the date and time, and as this is automatic, only the date will be known inherently (without manually checking the file).
I am using .Attachments.Add and format(date... etc.) to get the second part of the file name.
The first part is a number and a word which don't change
but the third part (shown as "*.csv" below) is the bit that is causing the issue.
I have tried to substitute * like I saw on a forum but it where it seemed to work in that example it is not working for me. Am I missing something?
.Attachments.Add ("G:\AML, CFT & Sanctions\Sanctions\KYC6 Person & Organsation Reports\" & Format(Date, "yyyy") & "\" & Format(Date, "mmmm") & "\65436546_Test_" & Format(Date, "yyyymmdd") & "*.csv")
As #Kostas suggested, you can find files by a glob with the Dir function. Note that it only returns filename, without a path.
Do handle the case when nothing or more than one file matches the pattern. (My code produces an error in these cases; error codes are taken from http://www.halfile.com/vb.html .)
Dim date_ As Date, pattern, dir_, filename As String: date_ = Date
dir_ = "C:\Users\Ivan\Documents\test & test\" & _
Format(date_, "yyyy\\mmmm\\")
pattern = "65436546_Test_" & Format(date_,"yyyymmdd") & "*.csv"
filename = Dir(dir_ & pattern)
If Len(filename) = 0 Then Error 53 'File not found
If Len(Dir()) <> 0 Then Error 58 'More than one matching file
<email>.Attachments.Add(dir_ & filename)
Build the file path first, test it and attach it if it's valid. As advised in comments, you need to supply a concrete file name, wildcards are not allowed.
Dim path_ As String, name_ As String, file_ As String
path_ = "C:\Some folder\"
name_ = "*.csv"
file_ = Dir(strPath & name_)
If Len(Dir(path_ & file_)) > 0 Then
.Attachments.Add path_ & file_
End If

VBA notation - backslash in quotations

A colleague at work made a macro and I need to edit it, but first I need to figure out how it works.
Sheet2.Pictures.Insert(importPath & "\" & partName & "\" & picName & ".png").Select
This line is (I think) where images are inserted into the excel document. I'm trying to figure out exactly how it works. I know importpath, partName and picName are variables he defined earlier. importPath is self explanatory, I don't know why part name is in there but I know what it is and picName is there because you enter the picture name in a certain cell and it searches for that name in the importPath to insert into the sheet.
Also what confuses me is the & and "\" I have no idea what these do.
Any help out there?
This is compiling a group of variables into a String that represents a path. For example, if:
importPath = "myPics"
partName = "2014"
picName = "flower"
Then the line
importPath & "\" & partName & "\" & picName & ".png"
will create the String
"myPics\2014\flower.png"
which is the full filename being passed to Sheet2.Pictures.Insert
You're constructing a full file path to an image in that line so the & concatenates all the string variables and the "\" is just manually adding the backslash characters you'd expect to see in any windows explorer or command line window.