删除年龄大于特定年龄的文件夹
问题描述:
这是我的功能不起作用。它永远不会进入删除调用,因为if语句永远不会评估为真,我无法弄清楚原因。删除年龄大于特定年龄的文件夹
Function DeleteOldFolders(root, maxAgeInDays)
Dim fso, ofolder, subFolders
Set fso = CreateObject ("Scripting.FileSystemObject")
If fso.FolderExists(root) Then
Set ofolder = fso.GetFolder(root)
Set subFolders = ofolder.SubFolders
For Each folder in subFolders
createdDate = FormatDateTime(folder.DateCreated, "2")
If (DateDiff("d", createdDate, Date) > maxAgeInDays) Then
objFSO.DeleteFolder folder, True
End If
Next
End If
Set objFSO = Nothing
End Function
答
为什么没有被删除的原因可能是你定义fso
Set fso = CreateObject ("Scripting.FileSystemObject")
但随后使用objFSO
objFSO.DeleteFolder folder, True
,并在您的脚本(永远,永远使用有On Error Resume Next
别处除非你知道正好你在做什么和有合理的错误处理代码)。
一些侧面说明(无关的实际问题,但值得考虑):
- 始终使用
Option Explicit
。没有例外。 - 您可以直接在
DateDiff()
中使用folder.DateCreated
。不需要格式化该值。 - 你的函数不返回任何东西,所以你最好使它成为一个过程。
你的程序的simpified版本看起来是这样的。
Sub DeleteOldFolders(root, maxAgeInDays)
Dim fso, folder
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FolderExists(root) Then
For Each folder in fso.GetFolder(root).SubFolders
If DateDiff("d", folder.DateCreated, Date) > maxAgeInDays Then
folder.Delete True
End If
Next
End If
Set fso = Nothing
End Sub
答
你的陈述
createdDate = FormatDateTime(folder.DateCreated, "2")
是错误的,危险的,也是不必要的。第二个参数 -
NamedFormat可选。指示使用的日期/时间 格式的数字值。如果省略,则使用vbGeneralDate。
是数字,并应通过预先定义的常量vbGeneralDate
给予,...。
无论所得串被正确地转换成由DateDiff()
所需的日期是个悬而未决的问题。因此,使用一贯类型
If (DateDiff("d", folder.DateCreated, Date) > maxAgeInDays) Then
的问题的另一个可能的原因是DateDiff()'
语义学:
如果DATE1指稍后的时间点比date2的,该则DateDiff函数 返回负数。
你作为maxAgeInDays
通过了什么?