VBA将自身复制到其他位置

发布于 2024-11-02 20:40:07 字数 273 浏览 3 评论 0原文

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

我尝试了这样的方法,

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

但是尽管我对所有涉及的目录具有完全访问权限,但我收到了访问受限异常。是因为我想“复制自己”吗?这可能吗?如果没有,我可以建立一个解决方法吗?

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

I tried it like this

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

But I get an Access restricted Exception, 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苏佲洛 2024-11-09 20:40:07

尝试使用

ThisWorkbook.SaveCopyAs otherDir & "Test1"

ThisWorkbook.SaveAs otherDir & "Test2"

ThisWorkbook 引用包含您正在运行的宏的工作簿...

更新:这应该可以帮助您创建文件夹...

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

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

Try using

ThisWorkbook.SaveCopyAs otherDir & "Test1"

or

ThisWorkbook.SaveAs otherDir & "Test2"

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

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

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

 Dim fso As FileSystemObject
 Set fso = New FileSystemObject
 fso.CreateFolder ("C:\test\test2")
 ThisWorkbook.SaveCopyAs "c:\test\test2\ttt.xlsm"
浮萍、无处依 2024-11-09 20:40:07

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

首先,您需要将引用(菜单:工具 -> 引用)添加到 Microsoft 脚本运行时,然后使用 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

替代方案:将文档保存到新目标,然后将其保存回来。

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

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

First you will need to add a Reference (Menu: Tools->References) to the Microsoft Scripting Runtime and then use the 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文