VBA code for checking filename with a specifc format - vba

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().

Related

Opening Files in file path but being able to change the date on new workdays

I open multiple files at my job and would like to know how to open different files by concatenating a workday variable into the file path. Is this possible?
Code:
Sub File_Demo()
Dim pathname
Dim Date_X
Dim Date_Y
Date_X = “02.01.22”
Date_Y = 20220201
Pathname =
“C:\Users\Jinx\Desktop\PDF_Files\2022\Feb\& Date_X &\PDF_FileName & Date_Y &.pdf”
ActiveWorkbook.FollowHyperlink pathname
End Sub
I would use this code to open multiple files at once by using a workday - 1, -2, -3, etc type of variable but am stuck on where to start in this process.
The Date Keyword can be used in VBA to get the current date value. The Format function can then turn the date value into whatever format you supply. On that article I linked above, they give a useful chart of how to create a date format.
Format(Date, "mm.dd.yy") would be "02.18.22" today and "02.19.22" tomorrow.
Format(Date, "yymmdd") would be "220218" today and "220219" tomorrow.
If you need pieces of the current date, like the Year or the Month you can use the aptly named Year and Month functions. Year(Date) would return 2022. And Month(Date) would return 2. If you need the month as a three-letter abbreviation, Format(Date, "mmm") would give you "Feb".
So for your file path you can do:
Pathname = "C:\Users\Jinx\Desktop\PDF_Files\" & Year(Date) & "\" & Format(Date, "mmm") & "\" & Format(Date, "mm.dd.yy") & "\PDF_FileName" & Format(Date, "yymmdd") & ".pdf"
If you need to change the date, and re-build the pathname, simply replace Date with a different value. You can even have a loop like
'From yesterday to three days from now
For myDate = Date - 1 to Date + 3
Pathname = "C:\Users\Jinx\Desktop\PDF_Files\" & Year(myDate) & "\" & Format(myDate, "mmm") & "\" & Format(myDate, "mm.dd.yy") & "\PDF_FileName" & Format(myDate, "yymmdd") & ".pdf"
'Do Stuff
Next
Notes: I also noticed that the quotation marks in your post were not standard " marks. That will cause an error in VBA since they will register as unrecognized symbols. Additionally, strings must be concatenated with & symbols, but those must be outside the quotation marks.
Eg. myString = "abc" & "def"
NOT myString = "abc&" "def"

How do I increment emails by 1 when I Save As in a directory?

I've had the hardest time figuring out the below code
I am trying to save many files over the course of a day into one directory with the same name, except with a number that marks it in a successive fashion.
I have searched stackoverflow, but cannot seem to understand where I put the Save As line, within the loop to increment by one? Well, that didn't work and neither did many other tries.
Please kindly advise on this :)
Sub AutoSave()
Dim filename As String, filepath As String, filecount As Integer, filedate
As String
filedate = Format(Now(), "MM-DD-YYYY")
filepath = "C:\Users\nabil\OneDrive\Documents"
filecount = filecount + 1
Set book = Workbooks.Open("Nabil 06-06-2019 #1 Lincoln.xlsx")
' code to copy and paste here
If Len(Dir(filepath & filename)) <> 0 Then
filecount = filecount + 1
filename = "Nabil " & filedate & " " & "#" & filecount & " " & "Lincoln"
ActiveWorkbook.SaveAs filename:= _ "C:\Users\nabil\OneDrive\Documents\Nabil
" & filedate & " " & "#" & filecount & " " & "Lincoln" & ".xlsx"
End If
End Sub
Thanks for the help Mathieu. I have now edited it like this above
But now it does not want to Save As , when I put the save as in the loop or if-then statement. If I put it after the loop , then it prompts me to save over the existing file name, not saving as the file name with an increment of 1 (.e.g, #2)
This is a sliver of the code I'm using which requires that I operate from the macro workbook and open a blank template and paste data onto it , and then save as throughout the day
Please kindly advise :)

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

Changing Day and Month to DD and MM format in VBA

To give some context here, I have a dat file that I am trying to save as an xlsx on my Q drive. I know that the majority of the code works (I've tested it), so I don't want to completely change it, but the formatting as I explain below is what I need help with. The following code is in workbook1 and it is referencing workbook2. Cell D3 in workbook one is a date formula but unfortunately, the FileDay and FileMonth code will only pull in a single "d" or "m" when what I want is it to pull in days and months in the "dd" and "mm" format. Since the code below is trying to find a file in this format: "yyyy_mm_dd" but FileDay and FileMonth are only pulling in "d" and "m", it will only work during part of the year. What is the piece of code that I am missing to pull in the correct formatting from cell D3?
Dim FName As String, FPath As String
Dim wkb1 As Workbook, wkb2 As Workbook
Set wkb1 = ThisWorkbook
FileDay = Day(Range("D3"))
FileMonth = Month(Range("D3"))
FileYear = Year(Range("D3"))
FPath = "Q:\MyFolder"
FName = "MyFile_" & FileYear & "_" & FileMonth & "_" & FileDay & ".xlsx"
Set wkb2 = Workbooks("MyFile_" & FileYear & "_" & FileMonth & "_" & FileDay
& ".dat")
With wkb2
.SaveAs Filename:=FPath & "\" & FName
.Close True
End With
End Sub
Assuming these variables are Strings, use the Format$ function.
FileDay = Format$(Day(Range("D3")), "00")
FileMonth = Format$(Month(Range("D3")), "00")
FileYear = Format$(Year(Range("D3")), "0000")
Alternatively, do it all at once:
= Format$(Range("D3"), "YYYY_MM_DD")

Creating a macro that resets file and saves as new day

At work, I've been trying to create a macro that will automatically clear a certain range - only content -, the range being B78:G83.
After clearing this range, I'd like the macro to save the current file under a new name. The new name should be the current day, with format "dd mmmm" (two digits for the name, a space in between and then the full month's name)
The file path is (f.e.)
"T:\RESERVATIONS\Duty Report\2017\4. April\25 april"
with the year, month and current date being variable (as we make separate folders for these files at work).
Sub NieuweDag()
'
' NieuweDag Macro
' Invoer wissen en opslaan als nieuwe dag
'
' Sneltoets: Ctrl+q
'
Range("B78:G83").Select
Range("G82").Activate
Selection.ClearContents
Dim FilePath As String
Dim NewName As String
FilePath = "T:\RESERVATIONS\Duty Report\": NewName = FilePath & Year(Now()) & "\" & Month(Now()) & ". " & MonthName(Now()) & "\" & Format(Date, "dd mmmm") & ".xlsm"
ActiveWorkbook.SaveAs Filename:=NewName, FileFormat _
:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub
This is what I've got but it doesn't work. I get Error 5. It's in dutch, so allow me to translate:
Error 5 during launch:
Invalid procedure-call or invalid argument
Anyone out here be able to help me out?
The proper format is MonthName(number of month, [abbreviate]), you should use
MonthName(Month(Now()))
instead of
MonthName(Now())
Plus, you can enhance your code by using
Range("B78:G83").ClearContents
instead of
Range("B78:G83").Select
Range("G82").Activate
Selection.ClearContents
You can reduce the amount of coding required to create NewName by changing
NewName = FilePath & Year(Now()) & "\" & Month(Now()) & ". " & MonthName(Now()) & "\" & Format(Date, "dd mmmm") & ".xlsm"
to
NewName = FilePath & Format(Now(), "yyyy\\m. mmmm\\dd mmmm") & ".xlsm"