Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the current directory as path in VBA?

Tags:

excel

vba

I have a macro-enabled WorkBook. I need to specify the current folder in which the macro-enabled file is present as the path. I tried setting

path = ActiveWorkbook.Path

and

path = CurDir()

but neither of these work for me. Any idea on this?

like image 450
user1270123 Avatar asked Apr 18 '12 18:04

user1270123


People also ask

How do I create a directory path in VBA?

The Microsoft Excel MKDIR statement allows you to create a new folder or directory. The MKDIR function is a built-in function in Excel that is categorized as a File/Directory Function. It can be used as a VBA function (VBA) in Excel.

How do I change the current directory in VBA?

“ChDir” can be termed as “Change Directory.” By using “ChDir,” we can change the current default directory used in VBA when searching for the files without a fully qualified path. For example, when we try to save the file as a new file by default, we can see the system configured drive opens up.

What does dir () do in VBA?

Dir returns the first file name that matches pathname. To get any additional file names that match pathname, call Dir again with no arguments. When no more file names match, Dir returns a zero-length string (""). After a zero-length string is returned, you must specify pathname in subsequent calls, or an error occurs.


2 Answers

If the path you want is the one to the workbook running the macro, and that workbook has been saved, then

ThisWorkbook.Path

is what you would use.

like image 132
Tim Williams Avatar answered Sep 22 '22 12:09

Tim Williams


I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _
like image 32
Siddharth Rout Avatar answered Sep 19 '22 12:09

Siddharth Rout