VBA代码来删除包含特定字符的目录中的文件
我需要一个VBAmacros的帮助,它将删除包含2个以上“_”的目录中的文件,并且大于3个月以前,但目录中有一些文件夹和子文件夹不能被触摸或修改。
例如,Hi_Thanks_for_your_help 或 Hi_Thank_You等
Const DIR = "x" Const MAX_AGE = 3 ' Unit: Months Dim oFSO Dim aExclude Sub XLS() aExclude = Array("x") Set oFSO = CreateObject("Scripting.FilesystemObject") deleteFiles oFSO.GetFolder(DIR) Set oFSO = Nothing End Sub '================================= Function isExclude(sPath) Dim s, bAns bAns = False For Each s In aExclude If InStr(1, sPath, s, vbTextCompare) = 1 Then bAns = True Exit For End If Next isExclude = bAns End Function '================================= Function isOldFile(fFile) ' Old file if "MAX_AGE" months before today is greater than the file modification time isOldFile = (DateAdd("m", -MAX_AGE, Date) > fFile.DateLastModified) End Function
这是我用代码得到的最远,我缺less的是如何检查一个文件名是否包含多于2个“_”,如果是的话,它比3个月大=删除。
提前致谢! 干杯!
Dim pathname As String = "" If fileNameCount("file_name") And DateDiff("m", NOW(), FileDateTime(pathname)) > 3 Then ' if '_' is more than 2 count and more than 3 months old, then delete ' if true delete file codes starts here ...... End If Public Function fileNameCount(filename As String) As Boolean fileNameCount = False Dim count As Long Dim temp() As String temp = Split(filename, "_") count = UBound(temp, 1) If (count > 2) Then fileNameCount = True End If End Function
我已经为你写了一部分代码,fileNameCount方法会返回你真/假计数的数字'_',我使用DateDiff来获取文件的月份的差异。 因此,我正在检测这两个条件,如果两个陈述是真实的情况,那么你应该继续删除我没有写的文件代码。
你需要做的是
1)传入“file_name”参数,您需要考虑如何获取文件名
2)传入文件的正确path名
3)编写删除文件的代码
无论如何,我没有testing代码,所以它可能有一些错误(S)。 希望这将有助于你想要做什么。
要在文件中获得"_"
的数量,我会使用类似这样的东西:
Dim a Dim c As Integer a = Split("File_Name_Here", "_") c = Ubound(a)
使用这个,你知道如果文件名被分割成3个或更多的子string,文件名中有2个"_"
。 至于文件的年龄, FileDateTime("FilePath")
将得到您创builddate或最后修改date。
- 如何在PowerPivot中计算一对多关系中的行数
- 我在VBA中有一组Sub()。 我想写一个代码设置一个优先级,哪个潜艇应该作为第一个和后来运行
- closuresfilter
- VBA:search其他文本中的文本,返回相邻的单元格。 循环这个
- 如何捕捉错误和debugging在Visual Studio 2010下在C ++中创build的Excel DLL插件?
- 有没有办法通过点击上面的对象来select一个单元格?
- 在打开由OpenXML SDK 2.5创build的Excel文件时出现错误
- 在TextToColumns中正确设置FieldInfo时,不应该将文本转换为MS Access的文本?
- 从C#打开Excel文件