VBA 将自身复制到其他位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5745013/
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-11 13:04:55  来源:igfitidea点击:

VBA copy self to other location

vbaexcel-vbadirectorycopy-pasteexcel

提问by F.P

I have an Excel-Macro in VBA in which I want to copy the file from where the macro is executed into another location.

我在 VBA 中有一个 Excel 宏,我想在其中将执行宏的文件复制到另一个位置。

I tried it like this

我这样试过

Call FileCopy(currentDir & "\" & Filename, _
otherDir & "\" & Filename)

But I get an Access restrictedException, although I have full access to all of the directories involved. Is it because I'm trying to "copy myself"? Is this possible? If not, could I build a workaround?

但是我得到一个Access restricted例外,尽管我可以完全访问所有涉及的目录。是因为我试图“复制自己”吗?这可能吗?如果没有,我可以建立一个解决方法吗?

回答by The King

Try using

尝试使用

ThisWorkbook.SaveCopyAs otherDir & "Test1"

or

或者

ThisWorkbook.SaveAs otherDir & "Test2"

ThisWorkbook refers to the workbook which contains the macro you are running...

ThisWorkbook 是指包含您正在运行的宏的工作簿...

Update: This should work for you to create a folder...

更新:这应该适合您创建文件夹...

Make sure you add "Microsoft Scripting Runtime" under Tools -> references.

确保在“工具”->“引用”下添加“Microsoft Scripting Runtime”。

 Dim fso As FileSystemObject
 Set fso = New FileSystemObject
 fso.CreateFolder ("C:\test\test2")
 ThisWorkbook.SaveCopyAs "c:\test\test2\ttt.xlsm"

回答by marg

Using FileCopy didnt work for me either but using CopyFile from FileSystemObject seems to work.

使用 FileCopy 对我也不起作用,但使用 FileSystemObject 中的 CopyFile 似乎有效。

First you will need to add a Reference (Menu: Tools->References) to the Microsoft Scripting Runtime and then use the FileSystemObject

首先,您需要向 Microsoft Scripting Runtime 添加一个 Reference(菜单:Tools->References),然后使用 FileSystemObject

Dim fso As FileSystemObject
Set fso = New FileSystemObject

fso.CopyFile currentDir & "\" & Filename, otherDir & "\" & Filename, True
''the last parameter decides weather or not you want to overwrite existing files

Set fso = Nothing

Alternative: Save the document at the new destination and then save it back.

替代方法:将文档保存在新的目的地,然后再保存回来。

ThisWorkbook.SaveAs otherDir & "\" & Filename
ThisWorkbook.SaveAs currentDir & "\" & Filename