ExcelVBA之复制文件

使用FileCopy语句,可以在文件夹之间复制文件:
FileCopy 来源, 目的地

该语句的第一个参数是文件来源,明确你要复制的文件名称,该名称可以包含驱动名称。第二个参数是复制的目的地,可以包括驱动和文件夹的地址。两个参数都是必须的。假设你要将用户确定的一个文件复制到一个叫做“C:\try”的文件夹,下面的过程示范如何完成它:

Sub CopyToAbort()
Dim folder As String
Dim source As String
Dim dest As String
Dim msg1 As String
Dim msg2 As String
Dim p As Integer
Dim s As Integer
Dim i As Long
On Error GoTo ErrorHandler
folder = "C:\try"
msg1 = "The selected file is already in this folder."
msg2 = "was copied to"
p = 1
i = 1
' get the name of the file from the user
source = Application.GetOpenFilename
' don't do anything if cancelled
If source = "False" Then Exit Sub

' get the total number of backslash characters "\" in the source

' variable?s contents
Do Until p = 0
p = InStr(i, source, "\", 1)
If p = 0 Then Exit Do
s = p
i = p + 1
Loop
' create the destination file name
dest = folder & Mid(source, s, Len(source))
' create a new folder with this name
MkDir folder
' check if the specified file already exists in the
Print
' destination folder
If Dir(dest) <> "" Then
MsgBox msg1
Else
' copy the selected file to the C:\Abort folder
FileCopy source, dest
MsgBox source & " " & msg2 & " " & dest
End If
Exit Sub
ErrorHandler:
If Err = "75" Then
Resume Next
End If
If Err = "70" Then
MsgBox "You can't copy an open file."
Exit Sub
End If
End Sub

过程CopyToAbort使用了Excel应用程序的方法GetOpenFilename从用户那里获取文件名称。该方法导致弹出内置的打开对话框。使用该对话框,你可以在任何驱动的任何文件夹里选择任何文件。如果用户取消了,VB就返回值“False”并且程序结束。

参考文章:https://www.w3cschool.cn/excelvba/excelvba-filecopy.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值