VBA - How to get the last modified file or folder in a directory in Excel 2010 - excel

What I want to do is more complex than selecting a file from a list of files. I will start in a directory, then I want to change to the most recently modified directory. I then want to repeat that process in a sub-directory, and then, inside of that, I want to select the most recently modified excel file and open it.
What is the best approach to do this?
What objects / methods should I be looking into?

The simplest function is
FileDateTime(pathname)
where pathname can be a directory for folder.
Alternatively, you can use the FileSystemObject object, DateLastModified property:
Dim fileModDate As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(<filenamestringhere>)
fileModDate = f.DateLastModified
All of the above can be explored in VBA help.

Related

Do the DSOFile functions only apply to the non-binary Excel Document types?

Using Windows 10 (Build 1903 if that's relevant?) and 64bit Office 365 (probably relevant?) I've implemented a system that allows me to version control Excel VBA code.
I'm using the Workbook_BeforeSave method to check whether the current file is saved or not, and if it is saved, where it is saved to.
This works fine and will prompt the user as to whether they want to update the code contained within. I then thought that maybe I should in fact check if the code "needs" to be updated prior to prompting the user.
First off, I found the following question/solution: Using VBA to read the metadata or file properties of files in a SharePoint doc library
which I couldn't use without DSOFile.dll that I was able to install from here:
https://www.microsoft.com/en-us/download/details.aspx?id=8422
Here follows the code I have which doesn't work:
Private Function CheckTemplateIsNewerThanCurrentFile(ByVal templatePath As String) As Boolean
Dim templateName As String
Dim fso As New FileSystemObject
templateName = ActiveWorkbook.CustomDocumentProperties("TemplateName").Value
If fso.FileExists(templatePath & "\" & LocalTemplateName) Then
Dim objDSO As New DSOFile.OleDocumentProperties
objDSO.Open templatePath & "\" & LocalTemplateName, True, dsoOptionDefault
If Not objDSO.CustomProperties("LastCommitDate") = ActiveDocument.CustomDocumentProperties("LastCommitDate").Value Then
CheckTemplateIsNewerThanCurrentFile = False
Else
CheckTemplateIsNewerThanCurrentFile = True
TemplateLastCommitDate = objDSO.CustomProperties.Item("LastCommitDate")
End If
End If
End Function
And here (highlighted) is the error I receive trying to run the method above on an .xlsb file:
(FWIW: the reason for use of the .xlsb format is because we're working with 500K+ rows of data in the process we're carrying out. Yes, I know Excel is ABSOLUTELY NOT the tool for this but we're lumbered with it now)
I know I could have already tried changing the file format to .xlsm but because this file is version controlled that is a pain to do if the method is still likely to fail.
Thanks in advance,
Alex.

How to define a specific application to open a pdf from excel

I would like to automate the opening of a pdf which is defined using a dynamic hyperlink, but using the DEFAULT pdf editor of the user, but cannot fathom how to do this beyond the code below which opens the file in
I have other code to save the pdf which automatically saves it and opens a file in the default program for each user. But I don't know how to do the reverse and have a file which is searched for and found via the dynamic hyperlink - which will then allow them to update.
This is to shortcut sometone opening various folders, manually seatching, then opening up a file. ideally Id want to automate.
Here is the code I have so far which works but will only open in Adobe and not the default program - is this perhaps a setting thing on my PC or is it code which is missing?
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("TNR Report")
Dim r As Range: Set r = ws.Range("A82") ' this defines the actual path and filename to be searched for
Dim strHyperlink As String
On Error GoTo CannotFindFile
strHyperlink = r.Value
ThisWorkbook.FollowHyperlink strHyperlink
File needs to open with nuance to enable the user to edit and update the "record", but opens only in reader which is no use and kind of defeats the purpose of the code.
2 possibilities:
Make Nuance your default application in Windows to open PDF files.
Use a shell command to start nuance with a filename as parameter
Shell """C:\Path To Nuance\Nuance.exe"" ""C:\Path To PDF\pdffile.pdf"""

How can i define the file path when opening workbook?

I have a macro that opens a workbook (each time a different one) and imports data from it. But when I activate it, the standard path is to my documents. How can i define a file path to a specific folder?
If you're looking for a way to change the default directory for choosing a file you would use:
ChDir (ThisWorkbook.Path)
However, if you're looking for some way to open a specific filepath, you would have to use a FilePickerDialog, assign a String to that user input, then use something like:
[StringVarName] = Application.GetOpenFilename
If you post your code with your attempt at fixing the issue, we would be able to better assist.

Excel VBA Dir() default path?

I am working through an exercise that uses Dir() to find out whether a file exists in the current directory (i.e. the same directory as the workbook I'm using). The code given - and apparently working in the video example - is like this:
IsThere = (Dir("SomeFile.xlsx") <> "")
When I run this code, IsThere returns False. I can work around it by using:
IsThere = (Dir(ActiveWorkbook.Path & "\SomeFile.xlsx") <> "")
but I want to know why Dir isn't looking by default in the current directory as expected.
I'm struggling to find any relevant advice on this. Most of the examples I've found of how to use Dir() are with the file path specified so they don't really shed any light on my problem. The closest I've found is this (obsolete) MSDN reference which says that:
To run correctly, the Dir function requires the Read and PathDiscovery flags of FileIOPermission to be granted to the executing code.
Trouble is, I don't really understand the linked advice in there on how to set PathDiscovery to 1.
As for StackOverflow, this is probably the closest to my problem - although this uses a specified path, and I am not referencing a network location. I note that the answer to this question seems to presume that Dir() should work in the way expected i.e. with a simple filename and not a fully specified path.
This has nothing to do with whatever the host application thinks it's directory is. You can always find out what directory Dir will default to by calling the CurDir function:
Debug.Print CurDir$
If you need to change it, call ChDir:
Debug.Print CurDir$
Debug.Print Dir$("*.*")
ChDir "C:\"
Debug.Print CurDir$
Debug.Print Dir$("*.*")
Think of it like sitting at a command prompt and typing dir or cd - it does exactly the same thing. Note that the current directory holds it's state between macro executions, so you can't rely on it being in some default location.
If you need a path relative to an open Workbook, use Workbook.Path if you need a path relative to the default path, use Application.Path. If you need to test for the existence of a file, don't use Dir at all - use the Scripting.FileSystemObject instead. You'll do yourself a huge favor if start thinking of the legacy file functions as deprecated.
Check the Excel Options --> Save --> Default File location to see what your default is. It won't by default use where the file is located.

Relative paths links in excel

I have an excel file with some email links. I would like to have a clickable link to download those files.
Having the two files (the excel and the email) in the same folder, the link file://test.eml or only test.eml does not open it, I need to use an absolute path. There would be a way to do this?
Thanks
EDIT
The absolute path is a known value, but anyway, the file is not opened.
=HYPERLINK("C:\Users\blanca.hernandez\Desktop\2012-05-24T09-41-11-0.00007.eml", "email")
It is funny, because something like
file://C:\Users\blanca.hernandez\Desktop\2012-05-24T09-41-11-0.00007.eml
gives me a clickabe link to open the file, but if I want to do the same with other directory, as
file://C:\repository\project\mail\archive\2012\5\24\11\2012-05-24T09-41-11-0.00007.eml
it is not possible to open. Are there some reasons for that?
You can use the Hyperlink(LinkLocation, FriendlyName") function in conjunction with Cell("filename")
Cell("filename") returns the full file name of the file that contains the reference as
C:\Full\Path\[FileName.xlsm]SheetName
To get just the path use
LEFT(CELL("filename"),FIND("*", SUBSTITUTE(CELL("filename"), "\", "*", LEN(CELL("filename")) - LEN(SUBSTITUTE(CELL("filename"),"\","")))))
Hyperlink(LinkLocation, FriendlyName") creates a hyperlink
To link to the file test.eml the full formula is
=HYPERLINK(LEFT(CELL("filename"),FIND("*",SUBSTITUTE(CELL("filename"),"\","*",LEN(CELL("filename"))-LEN(SUBSTITUTE(CELL("filename"),"\","")))))&"test.eml","Link to File")
MyPath = ActiveWorkbook.Path
that will give you the path to the workbook

Resources