要复制文件,可以使用VBA语句和FSO对象模型两种方式。
1 使用VBA语句复制文件
Sub 复制文件()
Dim SourceFile As String, DestinationFile As String
On Error GoTo err1
SourceFile = Application.GetOpenFilename(, , "选择源文件")
If SourceFile = "False" Then Exit Sub '用户选择"取消"则退出程序
DestinationFile = Application.GetSaveAsFilename(, , , "输入目标文件名")
If DestinationFile = "False" Then Exit Sub '用户选择"取消"则退出程序
FileCopy SourceFile, DestinationFile
MsgBox "复制成功!"
Exit Sub
err1:
If Err.Number <> 0 Then
MsgBox "无法复制该文件!"
End If
End Sub
2 使用FSO对象模型复制文件
Sub FSO复制文件()
Dim fso As New Scripting.FileSystemObject
Dim SourceFile As String, DestinationFile As String
On Error GoTo err1
SourceFile = Application.InputBox(prompt:="请输入当前文件夹中需要复制文件的名称:" & _
vbCrLf & "(可使用通配符):", Title:="输入文件名", Type:=2)
If SourceFile = "Fase" Or SourceFile = "" Then Exit Sub
DestinationFile = Application.InputBox( _
prompt:="请输入目标文件或文件夹(以“\ ”结尾)的名称:", _
Title:="目标文件", Type:=2)
If DestinationFile = "False" Or DestinationFile = "" Then Exit Sub
SourceFile = ThisWorkbook.Path & "\" & SourceFile '工作簿当前位置
fso.CopyFile SourceFile, DestinationFile, True '复制操作
MsgBox "复制成功!"
err1:
Set fso = Nothing
If Err.Number <> 0 Then
MsgBox "复制操作未完成!"
End If
End Sub
-End-