vba 如果文件存在则删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26927834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:14:18  来源:igfitidea点击:

vba if file exists then delete

excelvba

提问by james daley

I am trying to delete a text file where it contains part of the previous dates month in the file name title and the current year.

我正在尝试删除一个文本文件,其中在文件名标题和当前年份中包含上一个日期月份的一部分。

so for instance if today is November this would be month number 11 and last month would be month number 10.

因此,例如,如果今天是 11 月,这将是第 11 个月,而上个月将是第 10 个月。

so I want to delete the file where it contains month number 10 because this is the previous month.

所以我想删除包含第 10 个月的文件,因为这是上个月。

for some reason my code causes excel to crash and not respond, can someone please show me how I can alter my code to get this working, thanks

由于某种原因,我的代码导致 excel 崩溃并且没有响应,有人可以告诉我如何更改我的代码以使其正常工作,谢谢

Dim iMonth As Integer
Dim iYear As Integer
iMonth = Month(Date) - 1
iYear = Year(Date)
Dim DirFile As String
DirFile = "P:\Log (" & iMonth & "-" & iYear & ")*.txt"
Do While DirFile <> ""
Count = Count + 1
Loop
If Count > 0 Then
SetAttr DirFile, vbNormal
'Then delete the file
Kill DirFile
End If

回答by Steven Martin

Your giving the string DirFile a value then creating a while loop that loops while the string DirFile is not blank, so it will run forever (locking up excel), you will need code that will check if the file actually exists and then delete it

您给字符串 DirFile 一个值,然后创建一个 while 循环,当字符串 DirFile 不为空时循环,因此它将永远运行(锁定 excel),您将需要代码来检查文件是否实际存在然后将其删除

DirFile = "P:\Log (" & iMonth & "-" & iYear & ")*.txt"
Do While DirFile <> ""  'always true
Count = Count + 1
Loop

Try use

尝试使用

Dim iMonth As Integer
Dim iYear As Integer
iMonth = Month(Date) - 1
iYear = Year(Date)
Dim DirFile As String
DirFile = "P:\Log (" & iMonth & "-" & iYear & ")*.txt"

    If Len(Dir(DirFile)) <> 0 Then
        SetAttr DirFile, vbNormal
        Kill DirFile
    End If