使用 VBA 在当前目录中保存 Excel 工作表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4497646/
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
Saving an Excel sheet in a current directory with VBA
提问by Ndiol Dia
I have created a sheet in vba Excel. I would like to save it the current directory, but not in absolute path, then, when this is executed somewhere else, there won't be problem.
我在 vba Excel 中创建了一个工作表。我想把它保存在当前目录中,但不是绝对路径,那么,当它在其他地方执行时,就不会有问题。
Can somebody help ?
有人可以帮忙吗?
回答by Alex P
I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Pathto get a relative file path:
我不清楚您的情况到底需要什么,但以下内容可能会让您开始。这里的关键是使用ThisWorkbook.Path获取相对文件路径:
Sub SaveToRelativePath()
Dim relativePath As String
relativePath = ThisWorkbook.Path & "\" & ActiveWorkbook.Name
ActiveWorkbook.SaveAs Filename:=relativePath
End Sub
回答by Dick Kusleika
VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.
VBA 有一个 CurDir 关键字,它将返回存储在 Excel 中的“当前目录”。我不确定影响当前目录的所有内容,但打开或保存工作簿肯定会改变它。
MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"
This assumes that the sheet you want to save has never been saved and you want to define the file name in code.
这假设您要保存的工作表从未被保存过,并且您要在代码中定义文件名。
回答by Jonas Arnout
If the Path is omitted the file will be saved automaticaly in the current directory. Try something like this:
如果省略路径,文件将自动保存在当前目录中。尝试这样的事情:
ActiveWorkbook.SaveAs "Filename.xslx"
ActiveWorkbook.SaveAs "Filename.xslx"
回答by Ceekay
Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:\property\california\sacramento\workbook.xlsx, use this to move the property to berkley:
更进一步,要将文件保存到相对目录,您可以使用替换功能。假设您将工作簿保存在:c:\property\california\sacramento\workbook.xlsx,使用它来将属性移动到伯克利:
workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "\" & "newFileName.xlsx"
Only works if your file structure contains one instance of the text used to replace. YMMV.
仅当您的文件结构包含用于替换的文本的一个实例时才有效。天啊。

