在 VBA 中删除文件 [英] Deleting a file in VBA
问题描述
使用 VBA,我该如何:
Using VBA, how can I:
- 测试文件是否存在,如果存在,
- 删除它?
推荐答案
1.) 检查 这里.基本上这样做:
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.) 如何删除文件.看看 this. 基本上使用 Kill 命令,但你需要考虑到可能性只读的文件.这里有一个功能给你:
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?
将此答案标记为社区维基,以便任何人都可以在需要时对其进行修改.
Marking this answer as community wiki so anyone can modify it if need be.
这篇关于在 VBA 中删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!