VBA 覆盖导入内容 - 使用 FileSystemObject 和 CopyFile 方法
VBA 覆盖导入内容 - 使用 FileSystemObject 和 CopyFile 方法
VBA 可以使用 FileSystemObject 对象和 CopyFile 方法来实现覆盖导入内容。
步骤:
- 引用 Microsoft Scripting Runtime 库。
- 创建一个 FileSystemObject 对象:
Dim fso As New FileSystemObject
- 使用 CopyFile 方法进行覆盖导入:
fso.CopyFile 'C:\source\file.txt', 'C:\destination\file.txt', True
其中,第一个参数是源文件路径,第二个参数是目标文件路径,第三个参数为 True 表示覆盖已存在的目标文件。
完整代码示例:
Sub ImportFile()
Dim fso As New FileSystemObject
Dim sourcePath As String, destPath As String
sourcePath = 'C:\source\file.txt'
destPath = 'C:\destination\file.txt'
If fso.FileExists(sourcePath) Then
fso.CopyFile sourcePath, destPath, True
MsgBox 'File imported successfully.'
Else
MsgBox 'Source file does not exist.'
End If
End Sub
注意:
- 将代码中的示例路径替换为实际的源文件路径和目标文件路径。
- 确保目标文件路径存在,否则代码会报错。
- 使用该方法覆盖导入时,目标文件会被完全替换。
原文地址: https://www.cveoy.top/t/topic/jA9t 著作权归作者所有。请勿转载和采集!