在VBA中删除文件 [英] Deleting a file in VBA

查看:165
本文介绍了在VBA中删除文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用VBA,我怎么能:


  1. 测试一个文件是否存在,如果是的话,
  2. 删除它?
  3. //www.tek-tips.com/faqs.cfm?fid=1936rel =noreferrer>这里。基本上做到这一点:$ b​​
    $ b pre $函数FileExists(ByVal FileToTest作为字符串)作为布尔
    FileExists =(Dir(FileToTest)< ;>)
    结束功能

    我会留给你出了需要的各种错误处理,但这些都是我会考虑的错误处理事项之一:


    • 检查传递的空字符串。

    • 检查文件名/路径中包含非法字符的字符串


    <2>如何删除文件。看这个。基本上使用Kill命令,但是你需要考虑到这个可能性的文件是只读的。这里有一个函数为你:

    $ $ p $ code $ Sub DeleteFile(ByVal FileToDelete As String)
    如果FileExists(FileToDelete)Then'See上面
    '首先删除readonly属性,如果设置
    SetAttr FileToDelete,vbNormal
    '然后删除文件
    Kill FileToDelete
    End If
    End Sub

    再一次,我将把错误处理留给你,再次考虑这些事情: / p>


    • 目录和文件的行为应该不同吗?用户是否必须明确指出他们想要删除一个目录?

    • 你想让代码自动重置只读属性,还是应该用户被给予某种指示,只读的属性设置? 编辑:标记这个答案作为社区wiki,所以任何人都可以修改如果需要的话。


      Using VBA, how can I:

      1. test whether a file exists, and if so,
      2. delete it?

      解决方案

      1.) Check here. Basically do this:

      Function FileExists(ByVal FileToTest As String) As Boolean
         FileExists = (Dir(FileToTest) <> "")
      End Function
      

      I'll leave it to you to figure out the various error handling needed but these are among the error handling things I'd be considering:

      • Check for an empty string being passed.
      • Check for a string containing characters illegal in a file name/path

      2.) How To Delete a File. Look at this. Basically use the Kill command but you need to allow for the possibility of a file being read-only. Here's a function for you:

      Sub DeleteFile(ByVal FileToDelete As String)
         If FileExists(FileToDelete) Then 'See above          
            ' First remove readonly attribute, if set
            SetAttr FileToDelete, vbNormal          
            ' Then delete the file
            Kill FileToDelete
         End If
      End Sub
      

      Again, I'll leave the error handling to you and again these are the things I'd consider:

      • Should this behave differently for a directory vs. a file? Should a user have to explicitly have to indicate they want to delete a directory?

      • Do you want the code to automatically reset the read-only attribute or should the user be given some sort of indication that the read-only attribute is set?


      EDIT: Marking this answer as community wiki so anyone can modify it if need be.

      这篇关于在VBA中删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆