Multiple variables from a single user input - excel

I'm writing some VBA code that should go through all Excel files in a specific folder (folder names always formatted with Month Year, e.g. May 2020). In my code I also need to use the individual "Month" and "Year" strings e.g. "May" and "2020", and the date format mm/??/yy e.g. 5/??/20 (the day doesn't matter, so I just put ? as a placeholder) which are stored as variables.
So far, I am using Application.FileDialog(msoFileDialogFolderPicker) to let the user choose the folder, and I'm using InputBox("") three times to get the strings and date.
Is there a way to condense this so that the user only has to do one to two things, instead of four?
According to this answer combo box in a date format it seems like a combo box could work (maybe getting the month and year inputs as strings and getting the folder and date based on that?), but is there a better a way?
Any help would be appreciated!

This is the way it might work.
Ask the user for a date
From the date the macro creates the folder name
The path of the folder is stored in the macro
The code below implements and supports that work flow.
Sub GetFolderName()
Dim Inp As String
Dim FolderName As String
Dim FilePath As String
' make sure you ask for a date format that your computer can recognise
' it depends upon your Regional Settings (in Windows Control Panel)
Do
Inp = InputBox("Enter a date", "Date format dd/mm/yy", _
Format(Date, "dd/mm/yy"))
If Inp = "" Then Exit Sub ' blank or Cancel
If Not IsDate(Inp) Then
MsgBox "Sorry, I can't recognise your entry" & vbCr & _
"as a date. Please observe the date" & vbCr & _
"format requirement and try again."
End If
Loop While Not IsDate(Inp)
FilePath = Environ("userprofile") & "\Desktop\"
FolderName = Format(CDate(Inp), "mmmm yyyy")
MsgBox "Folder name is """ & FolderName & """" & vbCr & _
"File path = " & FilePath
' complete path is
Debug.Print FilePath & FolderName
End Sub
Note that the following options were not utilized but are still available.
Day(Cdate(Inp)) ' returns the day of the entered date
Month(Cdate(Inp)) ' returns the number of the month of the entered date
Year(Cdate(Inp)) ' returns the year of the entered date (45-digit)

Related

Exporting excel file to pdf with the file name as combined information from a Cell and the date and a word

I am coding in VBA in excel. I am trying to export an excel file as a pdf. I want the name of the pdf file to be a combination of multiple things: Words (it's a name) from cell D3 & todays date & the word 'invoice'. Right now, the file exports, but it has the name 'combined' instead of showing Name09-12-202Invoice.
How do I get the 'combined' variable to reflect the Name & date & word invoice, and then get the pdf to have that name?
The code runs, just not as I am expecting. Since the exported pdf file has the name combined, instead of the information in the 'combined variable'.
I don't know if I need to have all of the dimensions for 'combined' to be a string. But if that's the case I don't know how to turn a date into a string dimension. Am I combining the clientname, client date, and client invoice variables together into one variable 'combined' properly? And primarily, why isn't the 'combined' at the end of saveLocation, not the information in the 'combined' variable?
Thank you to anyone who helps! I am new to VBA so I appreciate it!
Sub SaveActiveSheetsAsPDF()
'Create and assign variables
Dim saveLocation As String
Dim clientname As String
Dim clientdate As Date
Dim clientinvoice As String
Dim combined As String
clientname = Range("D3")
clientdate = Date
clientinvoice = "Invoice"
combined = clientname & clientdate & clientinvoice
saveLocation = "C:\Users\jessi\Documents\Info\combined.pdf"
'Save Active Sheet(s) as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=saveLocation
End Sub
Like this:
clientname = Range("D3").Value
clientdate = Format(Date, "yyyy-mm-dd") 'Make sure you don't end up with (eg) mm/dd/yyyy format...
saveLocation = "C:\Users\jessi\Documents\Info\" & _
clientname & "_" & clientdate & "_Invoice.pdf"
'Save Active Sheet(s) as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=saveLocation

Activating a closed workbook with dates using partial string seach

I have a file named "PLDriverSensitivityReportSIN__21112019_172032.xls"
"PLDriverSensitivityReportSIN__" is constant
"21112019" is the date that changes everyday
"172032" is random
I would like to have an Input box prompting " Key in today's date (ddmmyyyy)" and save this to a variable "Today"
Objective: The macro would prompt the user for today's date using the Input box and does a partial search in a specified directory for today's file. It should ignore the random element at end of the string.
The script should load the file based on the input "C:\Users\xxxx\Desktop\PLDriverSensitivityReportSIN__" & Today & "_*" & ".xls"
The current code I have is not dynamic - please see below
Set wkb2 = Workbooks.Open("C:\Users\xxxx\Desktop\PLDriverSensitivityReportSIN__21112019_172032.xls")
The following should help you achieve your desired result, it uses the Dir() function to find the Workbook using a wildcard then if the workbook is found, it will open it:
Sub OpenWildcard()
Dim sName As String
'Declare the variable for the workbook.
Today = InputBox("Enter Today's Date", "Enter Date")
'Prompt for date entry
'Today = Format(Date, "ddmmyyyy")
'Or use today's date without prompting the user for input
sName = Dir("C:\Users\xxxx\Desktop\PLDriverSensitivityReportSIN__" & Today & "_*" & ".xls")
'check if file is found
If sName <> "" Then
'if found then open
Workbooks.Open Filename:="C:\Users\xxxx\Desktop\" & sName
End If
End Sub

Editing an automated naming macro in excel (based on PC name and date, with variable save path)

I'm currently trying to get an excel file to save into YYYYMMDD_fixed name piece_INITIALS OF LAST PERSON TO EDIT.
I'm using Environ function to call the User's and PC's name in a cell that i've found can be used to add to the name.
The issues i'm trying to fix are:
how can i define the save path to work on any PC regardless of user name, as current path has Users/my name/ , and up to 4 people with different PCs and names will edit this file. it should just save on Desktop on any of the 4 PCs
how can i modify the
strFile = "C:\Users\me\Desktop\" & Format(dtDate, "ddmmyyyy") & ".xlsx"
part so that it displays YYYYMMDD_name (i get this part ok) _ABC where ABC value is in cell A1 generated by the below attr function?
the function used is
Function attr(choice) As String
Select Case (choice)
Case "computer": attr = Environ("Computername")
Case "user": attr = Environ("UserName")
End Select
End Function
and the one i use to save (albeit a different format on a different file) is
Dim dtDate As Date
dtDate = Date
Dim strFile As String
strFile = "C:\Users\me\Desktop\" & Format(dtDate, "ddmmyyyy") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=strFile, FileFormat _
:=51, CreateBackup:=False
Any help would be greatly appreciated!
Programming is not my main job, just trying to automate bits where possible, so go easy on me please :)
Maybe something like that will help:
Dim strFile As String, strUserName As String
Dim dtDate As Date
dtDate = Now
strUserName = attr("user")
strFile = "C:\Users\" & strUserName & "\Desktop\" & Format(dtDate, "ddmmyyyy") & "_" & Sheets("Sheet1").Range("A1").Value & ".xlsx"
MsgBox strFile
Note that I assigned the value of an active username to strUserName and I'm using it with your strFile. I also added Sheets("Sheet1").Range("A1").Value to the code (change sheet name accordingly). The final result will look like that:
C:\Users\username\Desktop\12082019_username.xlsx

Use Partial file name on import from SharePoint with Excel VBA

I'm trying to open, and import values to a workbook from another workbook. Both files are in SharePoint and in the same directory.
It works as long as the target file has a specific name. But the file will have a variable start and ending in the name. 5 varying numbers + name + varying date (72262-Faktureringsplan-2018-11-16).
I've tried using * but it seems it doesn't work with SharePoint. How can I use some kind of "wildcards" for accessing files names in SharePoint?
This is the part of the code that will load the file:
Sub faktureringsplan()
Dim FileName As String
FileName = ActiveWorkbook.Path & "\72262-Faktureringsplan-2018-11-16.xlsx"
Set wb = Workbooks.Open(FileName)
ThisWorkbook.Sheets(1).Range("B10:B31").Value = wb.Sheets(1).Range("B2:B23").Value
MsgBox ("Ferdig")
wb.Close
End Sub
This code is trying to look for very specific filename with '\72262-Faktureringsplan-2018-11-16.xlsx'
on line:
FileName = ActiveWorkbook.Path & "\72262-Faktureringsplan-2018-11-16.xlsx"
The way wildcard("*") works, is that it replaces the part you want to match with anything. So a simple change from the above to
"\72262-Faktureringsplan-*.xlsx"
would return filename that has any date starting with '72262-Faktureringsplan' in your case.
You could also make use of VBA's date function to find a matching filedate that has the same date as today's date.
Format(date, "YYYY-MM-DD")
would return today's date in the format "2018-11-16" (date of this reply).
Essentially, you can do something like this:
FileName = ActiveWorkbook.Path & "\*-Faktureringsplan-" & Format(date, "YYYY-MM-DD") & ".xlsx"
This would match the following: ANYTHING-Faktureringsplan-TODAY'S_DATE.xlsx

Excel vba Next invoice number with creation of automatic directory folder by month

Ok , here is the thing,
I have created a next invoice number program in which by pressing of a macro assigned button active invoice automatically saved and closed and the next invoice with a number increased appear.My problem is that, I want excel invoices to be created in their relevant folder by their first two digits of invoice number . as an example : 04-001 where 04 stands for April. also, when invoice number is given 05-002, the directory folder of may 2018-19 should be auto created and invoice should be there in the folder only. i am trying to figure out the code since some time but no luck till now. So far , The invoices are created according to date only but as darren said it is a problem for me when i am trying to create invoices from december on first day of january.
This is my current code :
Sub SaveInvoiceM()
Dim NewFN As Variant
If Len(Dir("C:\Invoices\" & Format(Date, "MMM YYYY") & "-" & (Format(Date, "YY") + 1), vbDirectory)) = 0 Then
MkDir "C:\Invoices\" & Format(Date, "MMM YYYY") & "-" & (Format(Date, "YY") + 1)
End If
' Copy Invoice to a New Workbook
NewFN = "C:\Invoices\" & Format(Date, "MMM YYYY") & "-" & (Format(Date, "YY") + 1) & "\Inv" & Range("F5") & ".xlsx"
ActiveWorkbook.saveas NewFN, FileFormat:=xlOpenXMLWorkbook
NextInvoice
End Sub
Range("F5") stands for my invoice number which is 04-001
I see what you are trying to do (keep nicely organized, automatically) and that's an excellent goal.
I have a suggestion of an alternate invoice numbering system (based on what I'm understanding of your situation & experience level) that will make tasks (like this "auto-filing" process) much easier, and will also simplify the process any time you (or especially anyone else) needs to look back at these invoices. There are a number of obvious benefits (same idea as metric vs imperial).
Ideal numbering system: (in my opinion)
To reduce confusion: Give each invoice and filename the same name instead of having a filename with a month and
Since you want granularity from months to years (but not days): make the invoice/file name include the all of those fields.
To make sorting & finding these logical (easier): place each "date part" in order of biggest to smallest. A unique sequential number goes at the very end.
Your code sample was a good start - I just have a bit of OCD when it comes to this kind of thing, and creation of a numbering system is an important task. (Also this will be "date-proof", and error-checked along the way...
This is a little different than what you had because instead of you telling the code what the next invoice number is, it tells you (by figuring out the next number in sequence based on the existing files).
Like yours, it creates a folder if necessary. Since the files are number YYMM-nnn then are always in the correct order when you sort them. (The "month folders" are unnecessary since the month is in the filename, but I included them anyway since that was your plan. You could just keep every month's invoices in one folder, and they'd still be organized in order of month.)
VBA #1: Save file with next sequential invoice number (creating folder if necessary)
Sub createInvoiceNumberAndSave()
'creates a new invoice number based on date in specified cell & creates new folder if necessary
'finds next unused invoice number & verifies that file is properly saved
Const invoicePath = "c:\invoices\" ' invoice root save path
Const fNamePrefix = "Inv" ' prefix for the filename
Const fNameExt = ".xlsm" ' file extension
Const getInvoiceDate = "F5" ' we GET the DATE of the invoice from F5
Const putInvoiceNumber = "F6" ' we will PUT the new filename into cell F6
Dim invDate As Date, folderName As String, fName As String, fNum As Long, nextInvoiceNum As Long
'get the invoice date and make sure it's valid
If IsDate(Range(getInvoiceDate).Value) Then
'valid date found in cell F5
invDate = Range(getInvoiceDate).Value
Else
'valid date not found in F5. Do we want to default to today's date?
If MsgBox("Cell " & getInvoiceDate & " does not contain a valid date." & vbLf & vbLf & _
"Do you want to use today's date instead?", vbQuestion + vbOKCancel, "Date not found") <> vbOK Then
Call MsgBox("Invoice Not Saved.", vbCritical + vbononly, "User Cancelled")
Exit Sub 'stop running
Else
invDate = Date 'use today's date
End If
End If
'find the next unused invoice number for this month
folderName = Format(invDate, "YYMM")
nextInvoiceNum = 0
'figure out the next unused "file number"
fName = Dir(invoicePath & folderName & "\" & fNamePrefix & folderName & "-*" & fNameExt)
If fName = "" Then
'file not found
If Dir(invoicePath & folderName, vbDirectory) = "" Then
'month not found - create folder?
If MsgBox("Okay to create folder '" & invoicePath & folderName & "' for invoice #" & folderName & "-001 ?", _
vbOKCancel + vbQuestion, "Folder not Found") <> vbOK Then Exit Sub
'create folder
MkDir (invoicePath & folderName)
End If
Else
'month found. Now find the highest invoice number in the folder.
Do While fName <> ""
Debug.Print "Found File: " & fName
'get the number (filename = fNamePrefix & "YYMM-___.xlsx" so we know where it is
If IsNumeric(Mid(fName, 6 + Len(fNamePrefix), 3)) Then 'it's a valid number
fNum = Val(Mid(fName, 6 + Len(fNamePrefix), 3))
'if it's the biggest so far, remember it
If fNum > nextInvoiceNum Then nextInvoiceNum = fNum 'biggest one so far
End If
fName = Dir
Loop
End If
'we have the next available invoice#
nextInvoiceNum = nextInvoiceNum + 1 'new invoice# (numeric)
'PUT the new invoice# (text) in cell F6
Range(putInvoiceNumber).Value = fNamePrefix & folderName & "-" & Format(nextInvoiceNum, "000")
fName = invoicePath & folderName & "\" & Range(putInvoiceNumber).Value & fNameExt
Debug.Print "Saving as: " & fName
'save file
ActiveWorkbook.SaveAs fName
'DOUBLE CHECK check that file exists (couple lines of code now save a headache later)
If Dir(fName) = "" Then
'something went wrong (file wasn't saved)
Call MsgBox("ERROR! FILE NOT SAVED: " & fName, vbCritical + vbOKOnly, "ERROR!")
Stop
End If
'success message!
Call MsgBox("Invoice saved successfully:" & vbLf & vbLf & fName, vbInformation, "Invoice Created")
'NextInvoice '?
End Sub
EDIT: ("Back to your way")
I can think of a number of ways that your method will be a problem, some of which I tried explaining, but you're determined to number & organize these files your way, so "here you go".
VBA #2: Save file with cell value as name:
This procedure saves the current file, named from the invoice number (like 04-001) that you enter in cell F5 (creating folder if necessary):
Sub SaveFileBasedOnInvoiceNumber()
Dim monthNum As Long, yearString As String, folderName As String, fName As String
'build filename
On Error Resume Next 'skip errors for now
monthNum = Val(Left(Range("F5"), 2))
yearString = Year(Date) & "-" & Right(Year(Date) + 1, 2)
folderName = "c:\invoices\" & StrConv(monthName(monthNum, True), vbUpperCase) & " " & yearString
fName = folderName & "\INV" & Range("F5") & ".xlsm"
'check if there was a problem
If Err Then MsgBox "Invalid invoice number": Exit Sub
MkDir (folderName) 'create folder
On Error GoTo 0 'turn error checking back on
'Confirm file saved properly
ActiveWorkbook.SaveAs fName 'save file
If Dir(fName) = "" Then MsgBox "Error! File not saved: " & fName: Exit Sub
MsgBox "Invoice saved successfully:" & vbLf & fName
End Sub
I'll leave "VBA #1" in the the top of the answer for others seeking a logical numbering & storage system with auto-generated invoice numbers.
(One day you'll figure out why that way would've been better, but be forewarned, it will be a lot more of a hassle to change your organization method later!)
Good luck!

Resources