简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM