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

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

Related

Wildcard for file path for adding attachments

I want to add attachments from a specific folder. I specified the file's path and two keywords which are fixed.
There are more characters to complete the file path after 'filename2' and before 'pmonth' which are not fixed and hence I need to use wildcard (*).
The code gives
'Couldn't find file'
I have gone through various threads and tried solutions. None works for what I want.
For ctr = 2 To lastrow
filename1 = Cells(ctr, 1).Value
filename2 = Cells(ctr, 3).Value
Set OutMail = OutApp.CreateItemFromTemplate(str_template)
path = "C:\Users\nikunj.v.tripathi\Desktop\" & filename1 & "_" & filename2 & " -" & "*" & pmonth & " " & syear & ".xlsx"
With OutMail
.Attachments.Add path ' <----- this line gives error
.To = Cells(ctr, 10).Value
.cc = Cells(ctr, 11).Value
.htmlbody = Replace(.htmlbody, "#Month#", smonth)
.htmlbody = Replace(.htmlbody, "#CLIENT NAME#", Cells(ctr, 1).Value
.Save
End With
Next ctr
To use the Dir function effectively in this case, you'll need the path and the file name as two separate variables. Assuming you add another variable called filename, you could then utilise the following code...
...
path = "C:\Users\nikunj.v.tripathi\Desktop\"
filename = filename1 & "_" & filename2 & " -" & "*" & pmonth & " " & syear & ".xlsx"
...
filename = Dir(path & filename) ' Dir returns the filename of the first file matching
' the criteria, or returns an empty string if no match.
Do Until filename = ""
.Attachments.Add path & filename
filename = Dir ' Using Dir again returns the next file matching
' the criteria, or returns an empty string if no match.
Loop
Of course - Attachments.Add adds a single attachment and returns the Attachment object. How can it possibly add multiple attachments?
You can use Scripting.FileSystemObject to loop through all files in a folder and add one attachment at a time. See, for example
https://devblogs.microsoft.com/scripting/how-can-i-get-a-list-of-all-the-files-in-a-folder-and-its-subfolders/

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!!!

VBA to find all CSV files in a Variable Folder name

I have a project to create VBA to find and open all CSV files in a folder that is named the current month. I found some stuff online that seemed close but not quite. They will eventually be converted to XLSX files and parsed. That part I have. The macro that converts, parses and saves will be housed in a different file along the same path but not as "deep".
So on my Desktop is a folder name "CSV find test". Inside are two folders "Feburary" and "March". I need it to open all csv files in the most recent month. I have the rest of the syntax. . . . .
I wouldn't imagine that it would take a huge amount of syntax. Thanks for any direction.
Sub OpenFile()
FileMonth = Month(Date)
FileDate = Format(Date, "mmmm")
FilePath = "C:\Users\Me\Desktop\CSV find convert tests\" & FileMonth & "\" & FileDate & ".xls"
Workbooks.Open Filename:="FilePath" <- - - - error happens here.
End Sub
I don't think you really understand how a variable works as you keep putting it in a string. If you put something in double quotes it creates a string. Below is how you can add the month to the string via the variable.
Sub OpenCSVs()
Dim MyFiles As String, ThisMonth As String
Dim startPath As String
ThisMonth = Format(Date, "mmmm")
startPath = "C:\Users\ME\Desktop\CSV find convert tests\" & ThisMonth & "\"
MyFiles = Dir(startPath & "*.csv")
Do While MyFiles <> ""
Workbooks.Open startPath & MyFiles
'Do stuff to it will go here
'ActiveWorkbook.Close SaveChanges:=True (Deactivated for now)
MyFiles = Dir
Loop
End Sub

VBA code for checking filename with a specifc format

I was looking for a vba code that could help me match a filename to a pre-specified format. I want it to color a cell red if it doesnt match the format.
For Eg: my format is alrt_OBU_PW_YYYYMMDD_HHMMSS.txt
If the file I browse using application.getopenfilename doesnt match this format, it should give me an error.
Thanks!
Here is what i have done till now-
I have copied the filename into a cell.
FileName = Sheets("Control Sheet").cells(2, "F").Value
If FileName = Format("alrt_OBU_PW_" & Format("yyyymmdd") & "_" & Format("hhmmss") & ".txt") Then
wqI.range("G21").Interior.ColorIndex = 43
Else: wqI.range("G21").Interior.ColorIndex = 3
End If
Please change the Format function with like below one:
Format("alrt_OBU_PW_" & Format(Now(), "yyyymmdd") & "_" & Format(Now(), "hhmmss") & ".txt"
Use correct/exact date & time instead Now().

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

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.