vba 如何在VBA中将当前目录指定为路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10215606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 12:59:44  来源:igfitidea点击:

How to specify the current directory as path in VBA?

excelvbaexcel-vba

提问by user1270123

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?

但这些都不适合我。对此有什么想法吗?

采纳答案by Siddharth Rout

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

我以为我误解了,但我是对的。在这种情况下,它将是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, _

回答by Tim Williams

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

如果您想要的路径是运行宏的工作簿的路径,并且该工作簿已保存,则

ThisWorkbook.Path

ThisWorkbook.Path

is what you would use.

是你会使用的。