Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current working directory using vba?

Tags:

excel

vba

I am using MS Excel 2010 and trying to get the current directory using the below code,

    path = ActiveWorkbook.Path

But ActiveWorkbook.Path returns blank.

like image 613
Ullan Avatar asked Nov 06 '13 22:11

Ullan


People also ask

What is Vbdirectory VBA?

VBA DIR function is also known as the directory function, this is an inbuilt function in VBA which is used to give us the file name of a given file or a folder but we need to provide the path for the file, the output returned by this function is string as it returns the name of the file, there are two arguments to this ...

Is there a today function in VBA?

Today means the current date, in worksheet Now function does the same thing which gives us the current date and time but there is no inbuilt today function in VBA itself, the method to get the current date of the system is by using the date function and unlike the now function date function only gives us the current ...

What is .range in VBA?

Range is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.


3 Answers

I've tested this:

When I open an Excel document D:\db\tmp\test1.xlsm:

  • CurDir() returns C:\Users\[username]\Documents

  • ActiveWorkbook.Path returns D:\db\tmp

So CurDir() has a system default and can be changed.

ActiveWorkbook.Path does not change for the same saved Workbook.

For example, CurDir() changes when you do "File/Save As" command, and select a random directory in the File/Directory selection dialog. Then click on Cancel to skip saving. But CurDir() has already changed to the last selected directory.

like image 99
jacouh Avatar answered Oct 09 '22 01:10

jacouh


You have several options depending on what you're looking for. Workbook.Path returns the path of a saved workbook. Application.Path returns the path to the Excel executable. CurDir returns the current working path, this probably defaults to your My Documents folder or similar.

You can also use the windows scripting shell object's .CurrentDirectory property.

Set wshell = CreateObject("WScript.Shell")
Debug.Print wshell.CurrentDirectory

But that should get the same result as just

Debug.Print CurDir
like image 12
AndASM Avatar answered Oct 08 '22 23:10

AndASM


It would seem likely that the ActiveWorkbook has not been saved...

Try CurDir() instead.

like image 8
Monty Wild Avatar answered Oct 08 '22 23:10

Monty Wild