在VBA中删除文件 [英] Deleting a file in VBA
问题描述
使用VBA,我怎么能:
- 测试一个文件是否存在,如果是的话,
- 删除它? //www.tek-tips.com/faqs.cfm?fid=1936rel =noreferrer>这里。基本上做到这一点:$ b
- 检查传递的空字符串。
- 检查文件名/路径中包含非法字符的字符串
-
目录和文件的行为应该不同吗?用户是否必须明确指出他们想要删除一个目录?
你想让代码自动重置只读属性,还是应该用户被给予某种指示,只读的属性设置? 编辑:标记这个答案作为社区wiki,所以任何人都可以修改如果需要的话。 - test whether a file exists, and if so,
- delete it?
- Check for an empty string being passed.
- Check for a string containing characters illegal in a file name/path
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?
$ 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>
Using VBA, how can I:
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:
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:
EDIT: Marking this answer as community wiki so anyone can modify it if need be.
这篇关于在VBA中删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!