VBA文件和文件夹操作

'创建文件夹
Function Create_folder(ByVal Path As String, ByVal FileName As String)
Dim folder As Object
'设置FSO对象
Set fso = CreateObject("Scripting.FileSystemObject")
'如果文件夹不存在就创建
'出错跳转

On Error Resume Next

If Not (fso.Folderexists(Path & FileName)) Then
    Set folder = fso.Createfolder(Path & FileName)
Else
    MsgBox "Folder already exists!", vbInformation, "ERROR:"
End If
'err: MsgBox "Error Number:" & err.Number & ",Please contact the program developer!", vbInformation, "ERROR:"
End Function

'拷贝文件
Function Copy_file(ByVal SourcePath As String, ByVal SourceFileName As String, ByVal TargetPath As String, ByVal TargetFileName As String)
Set fso = CreateObject("Scripting.FileSystemObject")
'判断源文件是否存在
'如果目标路径存在则拷贝文件,否则提示目录不存在
'如果目标位置存在同名文件则对其进行覆盖
'出错跳转

On Error Resume Next

If fso.Folderexists(SourcePath) And fso.Fileexists(SourcePath & SourceFileName) And fso.Folderexists(TargetPath) And (Not (fso.Fileexists(TargetPath & TargetFileName))) Then
    fso.Copyfile SourcePath & SourceFileName, TargetPath & TargetFileName, False
Else
    MsgBox "Possible errors:" & vbCrLf _
            & "1.The source file does not exist" & vbCrLf _
            & "2.Target path does not exist" & vbCrLf _
            & "3.The destination file already exists" & vbCrLf _
            , vbInformation, "ERROR:"
End If
End Function

'移动文件
Function Move_file(ByVal SourcePath As String, ByVal SourceFileName As String, ByVal TargetPath As String, ByVal TargetFileName As String)
Set fso = CreateObject("Scripting.FileSystemObject")
'判断源文件是否存在
'判断目标位置是否存在
'如果目标路径存在则拷贝文件,否则提示目录不存在
'如果目标位置存在同名文件则会报错
'出错跳转

On Error Resume Next

If fso.Folderexists(SourcePath) And fso.Fileexists(SourcePath & SourceFileName) And fso.Folderexists(TargetPath) And (Not (fso.Fileexists(TargetPath & TargetFileName))) Then
   fso.Movefile SourcePath & SourceFileName, TargetPath & TargetFileName
Else
    MsgBox "Possible errors:" & vbCrLf _
            & "1.The source file does not exist" & vbCrLf _
            & "2.Target path does not exist" & vbCrLf _
            & "3.The destination file already exists" & vbCrLf _
            , vbInformation, "ERROR:"
End If
End Function

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值