vba VBA将文件从一个目录复制到另一个目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16943003/
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
VBA to copy a file from one directory to another
提问by harryg
So I have an access file that I regularly need copied to another directory, replacing the last version. I would like to use an Excel macro to achieve this, and would also like to rename the file in the process.
所以我有一个访问文件,我经常需要将它复制到另一个目录,替换上一个版本。我想使用 Excel 宏来实现此目的,并且还想在此过程中重命名文件。
E.g.
例如
fileName = "X:\Database\oldName.accdb"
copyDestination = "Y:\dbstore\"
newName = "newName.accdb"
Is there an easy way of doing this?
有没有简单的方法来做到这一点?
回答by Jon
This method is even easier if you're ok with fewer options:
如果您可以选择较少的选项,则此方法会更容易:
FileCopy source, destination
回答by Bathsheba
Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:
在 Scripting.FileSystemObject 中使用适当的方法。那么您的代码将更易于移植到 VBScript 和 VB.net。为了让您开始,您需要包括:
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Then you could use
然后你可以使用
Call fso.CopyFile(source, destination[, overwrite] )
where source and destination are the full names (including paths) of the file.
其中 source 和 destination 是文件的全名(包括路径)。
See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method
请参阅https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method
回答by Galanor
One thing that caused me a massive headache when using this code (might affect others and I wish that somebody had left a comment like this one here for me to read):
使用此代码时让我非常头疼的一件事(可能会影响其他人,我希望有人在这里留下这样的评论供我阅读):
- My aim is to create a dynamic access dashboard, which requires that its linked tables be updated.
- I use the copy methods described above to replace the existing linked CSVs with an updated version of them.
- Running the above code manually from a module worked fine.
- Running identical code from a form linked to the CSV data had runtime error 70 (Permission denied), even tho the first step of my code was to close that form (which should have unlocked the CSV file so that it could be overwritten).
- I now believe that despite the form being closed, it keeps the outdated CSV file locked while it executes VBA associated with that form.
- 我的目标是创建一个动态访问仪表板,它需要更新其链接表。
- 我使用上述复制方法将现有的链接 CSV 替换为它们的更新版本。
- 从模块手动运行上述代码工作正常。
- 从链接到 CSV 数据的表单运行相同的代码有运行时错误 70(权限被拒绝),即使我的代码的第一步是关闭该表单(它应该已经解锁了 CSV 文件,以便它可以被覆盖)。
- 我现在相信,尽管表单已关闭,但它会在执行与该表单关联的 VBA 时锁定过时的 CSV 文件。
My solution will be to run the code (On timer event) from another hidden form that opens with the database.
我的解决方案是从另一个随数据库打开的隐藏表单中运行代码(On timer event)。