Hi there I am trying to make a macro that saves a report to a specific folder. Our folders get generated every day like C://Report_Type/2017/11/10 (where /10 is the folder I'd want to save the file to).
The code I have prompts the user to provide the date in order to have the folder located, and then it saves the file according to a specified name.
However when I run the macro it saves the file in the C://Report_Type/2017/11 root folder ignoring the day based on userinput. Could someone help where I got it wrong?
It's a bit complicated to explain, but if you check the code then it makes sense.
Sub PSSaveFile()
Dim myVal2 As Variant
Dim myDate As String
Dim mFilePath As String
myVal2 = InputBox("Please enter today's date in mm\dd format")
myDate = Date - 1
mFilePath = "\\sample\sample_emea\sec_REPORTS\APPS\Reports\Regional\sample_security_app\2017\" & myVal2
ActiveWorkbook.SaveAs FileName:=mFilePath & "SampleLogs-" & myDate & "-12352_checked"
End Sub
Thank you for the help in advance!
Why make it so complicated? I mean why ask for date when you can get that automatically?
Is this what you are trying (UNTESTED)?
Sub PSSaveFile()
Dim FilePath_A As String, FilePath_B As String, FilePath_C As String
Dim sFile As String
FilePath_A = "\\sample\sample_emea\sec_REPORTS\APPS\Reports\Regional\sample_security_app\2017\"
FilePath_B = Format(Date, "mm\dd")
FilePath_C = "\SampleLogs-" & Replace(Date - 1, "/", "-") & "-12352_checked.xlsx"
sFile = FilePath_A & FilePath_B & FilePath_C
ActiveWorkbook.SaveAs sFile, 51
End Sub
Few things
While naming files avoid the use of special characters like \ / : * ? " < > | and hence we use Replace(Date - 1, "/", "-") in the above code
Mention the file extention and file format number
Break your code in easy to understand "parts". makes it easier to understand and manage the code.
Yeah this one is a simpler approach, unfortunately the user who'll be using the macro often checks backlogs so the date she's reviewing isn't always today's or yesterday's date hence the userinput function – Rhyfelwr 14 mins ago
Since you are using InputBox you may want to use this
Sub PSSaveFile()
Dim FilePath_A As String, FilePath_B As String, FilePath_C As String
Dim sFile As String
Dim Ret As Variant
Ret = InputBox("Please enter date in mm\dd format")
If Ret = "" Then Exit Sub
FilePath_A = "\\sample\sample_emea\sec_REPORTS\APPS\Reports\Regional\sample_security_app\2017\"
FilePath_B = Ret
'~~> Check if the folder path exists
If FileFolderExists(FilePath_A & FilePath_B) Then
FilePath_C = "\SampleLogs-" & Replace(Date - 1, "/", "-") & "-12352_checked.xlsx"
sFile = FilePath_A & FilePath_B & FilePath_C
ActiveWorkbook.SaveAs sFile, 51
Else
MsgBox "The folder path " & FilePath_A & FilePath_B & " doesn't exist"
End If
End Sub
Public Function FileFolderExists(strFullPath As String) As Boolean
On Error GoTo Whoa
If Not Dir(strFullPath, vbDirectory) = vbNullString Then FileFolderExists = True
Whoa:
On Error GoTo 0
End Function
Related
I have a code that is list files in directory. how can I address code to look into parent directory of current workbook directory? i want it to be independent wherever I place it.
(first code addressing to the second one to read file from)
Thanks.
....
Application.ScreenUpdating = False
ShowPDFs "C:\Test\Working\", ws
ws.UsedRange.EntireColumn.AutoFit
Application.ScreenUpdating = True
End Sub
------------------------------
Private Sub ShowPDFs(ByRef fsoPath.......
Just check that the file is not at root level:
....
Application.ScreenUpdating = False
ShowPDFs ThisWorkbook.Path & "\..", ws
ws.UsedRange.EntireColumn.AutoFit
Application.ScreenUpdating = True
End Sub
------------------------------
Private Sub ShowPDFs(ByRef fsoPath.......
The solution you want:
If your behavior is to open an excel window and then open your recent file, please note that you should not forget to add change Drive and then change Directory into your VBA code.
Cause the Excel always start with the default Directory even it's just open your recent file !
Then, these should be help.
Solution A: You don't need to get parent directory to do anything else.
Dim ThisWorkbookPath As String
Dim ThisWorkbookPathParts As Variant
ThisWorkbookPath = ThisWorkbook.Path
ThisWorkbookPathParts = Split(ThisWorkbookPath, _
Application.PathSeparator)
ChDrive ThisWorkbookPathParts(LBound(ThisWorkbookPathParts))
ChDir ThisWorkbookPath
Solution B: You may need to get parent directory to do things else.
Dim ParentPath As String: ParentPath = "\"
Dim ThisWorkbookPath As String
Dim ThisWorkbookPathParts, Part As Variant
Dim Count, Parts As Long
ThisWorkbookPath = ThisWorkbook.Path
ThisWorkbookPathParts = Split(ThisWorkbookPath, _
Application.PathSeparator)
Parts = UBound(ThisWorkbookPathParts)
Count = 0
For Each Part In ThisWorkbookPathParts
If Count > 0 Then
ParentPath = ParentPath & Part & "\"
End If
Count = Count + 1
If Count = Parts Then Exit For
Next
MsgBox "File-Drive = " & ThisWorkbookPathParts _
(LBound(ThisWorkbookPathParts))
MsgBox "Parent-Path = " & ParentPath
We have a system that automatically downloads data and puts it in excel and other sheets. I am trying to write a macro for a master spreadsheet that retrieves the latest version of a certain file to edit, copy and paste into the master sheet.
I have trouble retrieving the file as the filenames include dates.
I am quite new to VBA and am still just throwing pieces of code together to get a working thing, but I cannot find exactly what I am looking for.
Filename is for example 'ML0003 - Daily Order Entry Information - 170927'
The last 6 figures represent the date and changes every time.
This is my code so far:
Dim dtTestDate As Date
Dim sStartWB As String
Const sPath As String = "D:\Berry\AddIn\Testing\"
Const dtEarliest = #1/1/2010#
dtTestDate = Date
sStartWB = ActiveWorkbook.Name
While ActiveWorkbook.Name = sStartWB And dtTestDate >= dtEarliest
On Error Resume Next
Workbooks.Open sPath & "ML0003 - Daily Order Entry Information - " & " ****** " & ".xls"
dtTestDate = dtTestDate - 1
On Error GoTo 0
Wend
If ActiveWorkbook.Name = sStartWB Then MsgBox "Earlier file not found."
I was under the assumtion that the asterix would allow any character there, but this does not seem to work. Any ideas?
You will want to use the Dir function to look for a file using the wildcard, like this:
Dim sFilename As String
While ActiveWorkbook.Name = sStartWB And dtTestDate >= dtEarliest
sFilename = Dir(sPath & "ML0003 - Daily Order Entry Information - *.xls*")
If sFilename <> "" Then Workbooks.Open sPath & sFilename
Wend
I have code to open a file with a variable date, as shown below. This code will not work without entering m.d.y.xls into the input box. I want to only have to enter m.d.y into the input box. Please take a look and let me know what I am missing. Thanks!
Dim wbkOpen As Workbook
Dim strFilePath As String
Dim strFileName As String
strFilePath = "D:\Users\stefan.bagnato\Desktop\Daily Performance Summary\Agent Group Daily Summary "
strFileName = InputBox("Enter last Friday's date in the format M.D.Y", "Friday's Date")
Set wbkOpen = Workbooks.Open(strFilePath & strFileName, False, True)
This is basic string concatentation:
strFilePath & strFileName & ".xls"
You should probably check to ensure the file exists, otherwise there will be an error:
Dim fullFileName As String
strFilePath & strFileName & ".xls"
If Dir(fullFileName) = "" Then
MsgBox "Invalid filename!"
Exit Sub
End If
Set wbkOpen = Workbooks.Open(fullFileName, False, True)
Ideally, you can avoid user-input (which is prone to error) altogether:
Const strFilePath As String = "D:\Users\stefan.bagnato\Desktop\Daily Performance Summary\Agent Group Daily Summary "
Dim wbkOpen As Workbook
Dim LastFridayDate As String
Dim fullFileName As String
Dim fdlg as FileDialog
LastFridayDate = Format(Date - (Weekday(Date, vbFriday) - 1), "m.d.yy")
fullFileName = strFilePath & LastFridayDate & ".xls"
If Dir(fullFileName) = "" Then
If MsgBox("The file named " & fullFileName & " doesn't exist. Would you like to manually locate the file?", vbYesNo) = vbNo Then
Exit Sub
Else
Set fdlg = Application.FileDialog(msoFileDialogOpen)
'## Opens the fileDialog in the normal folder where these files should exist
fdlg.InitialFileName = strFilePath
'## Display the fileDialog to the user
fdlg.Show
'## Validate the fileDialog hasn't been canceled
If fdlg.SelectedItems.Count <> 0 Then
'## Return the value of the item selected by the user
fullFileName = fdlg.SelectedItems(1)
Else:
MsgBox "No file selected, exiting procedure..."
End If
End If
End If
Set wbkOpen = Workbooks.Open(fullFileName, False, True)
Of course allowing the user to manually select the file may ultimately require additional validation and/or error-handling (i.e., what if they select the wrong file? How can the program know which date is the correct date [I'd wager that it can't, without doing an ugly brute force loop which still makes a lot of assumptions which might not always hold] What if they select a PDF or a PPT file instead of an XLS, etc. but those points are entirely out of scope for this question.)
If you have additional follow-ups, please follow proper site etiquette and ask a new question :)
When saving a specific workbook, Excel creates a temp file instead of saving the data (without displaying an error or warning message). The symptoms are roughly the same as described in this post:
microsoft-excel-returns-the-error-document-not-saved-after-generating-a-2gb-temp-file
I tried several solutions, but decided to implement a work-around as ‘save as’ is working ok.
The code below performs the ‘save-as’, based on having filenames ending with a value (e.g. myFile V1.xlsm), the macro will add an incremental character (a to z) each time the workbook is saved. (e.g. myFile V1a.xlsm).
The macro works fine in a standard module, but it causes Excel to “stop responding” when moved to ‘thisWorkbook’. I ‘solved’ this by keeping it in the standard module and assigning key combination ‘control-s’ to the macro. Still interested to know if it can be made to work in the ‘thisWorkbook’.
Drawback of this workaround is that each incremental save clogs up the ‘recent file’ list. It would be nice to remove the previous file name from the recent file history, but this seems not possible to do via VBA. (VBA - How do I remove a file from the recent documents list in excel 2007?). Any suggestions?
Windows 10, Excel 2016 (version 16.0.6868.2060)
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim newFilename As String
Dim oldFilename As String
oldFilename = ActiveWorkbook.Name
newFilename = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5)
If IsNumeric(Right(newFilename, 1)) = True Then
ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path + "\" + newFilename & "a.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
If Right(newFilename, 1) = "z" Then
MsgBox "'z' reached, please save as new version"
Exit Sub
End If
newFilename = Left(newFilename, Len(newFilename) - 1) & Chr(Asc(Right(newFilename, 1)) + 1)
ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path + "\" + newFilename & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End If
'potential code to remove oldFilename from 'Recent File' list
End Sub
I tested this Sub in Excel 2010 and it works for me. I immediately break the loop after deleting the file as I assume the indexing may get out of alignment with the loop. A more refined variant might loop through the recent file list and create a collection of indices to delete, then iterate backward over that collection and delete each entry in turn.
Public Sub RemoveRecentFile(strFileName As String)
Dim collRecentFiles As Excel.RecentFiles
Dim objRecentFile As Excel.RecentFile
Dim intRecentFileCount As Integer
Dim intCounter As Integer
Set collRecentFiles = Application.RecentFiles
intRecentFileCount = collRecentFiles.Count
For intCounter = 1 To intRecentFileCount
Set objRecentFile = collRecentFiles(intCounter)
If objRecentFile.Name = strFileName Then
objRecentFile.Delete
Exit For
End If
Next intCounter
End Sub
Thanks to Robin the working solution is as follows:
Updated intial code:
Sub incrementSaveAs()
'to avoid that other workbooks are saved (when assigned to shortkey control-S)
If ActiveWorkbook.Name <> ThisWorkbook.Name Then ActiveWorkbook.Save: Exit Sub
Dim newFilename As String
Dim oldFilename As String
oldFilename = ActiveWorkbook.Name
newFilename = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5)
If IsNumeric(Right(newFilename, 1)) = True Then
ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path + "\" + newFilename & "a.xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False, AddToMru:=True
'AddToMru:=True Added to update recent files history
Else
If Right(newFilename, 1) = "z" Then
MsgBox "'z' reached, please save as new version"
Exit Sub
End If
newFilename = Left(newFilename, Len(newFilename) - 1) & Chr(Asc(Right(newFilename, 1)) + 1)
ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path + "\" + newFilename & ".xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False, AddToMru:=True
End If
RemoveRecentFile (ActiveWorkbook.Path & Application.PathSeparator & oldFilename)
End Sub
Updated Robin's code:
Public Sub RemoveRecentFile(strPathAndFileName As String)
Dim collRecentFiles As Excel.RecentFiles
Dim objRecentFile As Excel.RecentFile
Dim intRecentFileCount As Integer
Dim intCounter As Integer
Set collRecentFiles = Application.RecentFiles
intRecentFileCount = collRecentFiles.Count
For intCounter = 1 To intRecentFileCount
Set objRecentFile = collRecentFiles(intCounter)
If objRecentFile.Path = strPathAndFileName Then
objRecentFile.Delete
Exit For
End If
Next intCounter
End Sub
Say I have the following path and file name:
P:\...\Annual and Quarterly Budget Data\ECMQA 2012Q1.xls
I want to write an if then statement that does the following (not sure if my statement is set up properly):
If InStr(1, "P:\...\Annual and Quarterly Budget Data\ECMQA 2012Q1.xls", "QA", vbTextCompare) > 0 Then
BD.Sheets("Sheet1").Range("C2").value = "2012Q1"
End If
Instead of just inputting "2012Q1", I want it to automatically read this from the file. The thing is I am actually looping through 12 or so files and there's two types, "ECMQA 2012Q1.xls" (or ECMQB 2012Q2.xls and so on) AND "ECM Annual Budget 2012.xlsx"
If my file is the annual one (If file contains "Annual"), then I want:
BD.Sheets("Sheet1").Range("C2").value = "2012"
And i want it to read this from the actual file, same as the other one...not me putting in "2012"
Is there a way to do this?
Any help will be appreciated!
EDIT:
Here is the loop:
Dim wb As Workbook, sFile As String, sPath As String
Dim itm As Variant
Dim strFileNames As String
sPath = "C:\Actuary\Cash Flow Forecast\Annual and Quarterly Budget Data\"
''Retrieve the current files in directory
sFile = Dir(sPath)
Do While sFile <> ""
strFileNames = strFileNames & "," & sFile
sFile = Dir()
Loop
''Open each file found
For Each itm In Split(strFileNames, ",")
If itm <> "" Then
Set wb = Workbooks.Open(sPath & itm)
''DO LOTS OF CALCULATIONS
'wb.Close True
End If
Next itm
Filesystemobject has a method for extracting the base name from a filename:
Msgbox createobject("scripting.filesystemobject").getbasename("myTest.xlsx") 'myTest
There's lots of ways to get at what you need using split, right, left, mid, or even regex. It really depends on the makeup of the possible source strings and how much variation they contain.
Based soley on your example the following shows various manipulations with the last variable giving "2012"
Sub test()
fPath = "P:\...\Annual and Quarterly Budget Data\ECMQA 2012Q1.xls"
fArray = Split(fPath, "\")
fnamewithtext = fArray(UBound(fArray))
fnamewithoutext = Split(fArray(UBound(fArray)), ".")(0)
ifannual = Left(Split(fArray(UBound(fArray)), " ")(1), 4)
End Sub