简体   繁体   English

Excel VBA-在动态文件名中删除日期

[英]Excel VBA- Remove Date in dynamic filename

I am amateur to VBA. 我是VBA的业余爱好者。

My objective is to zip the folder with multiple files which i have managed to achieve. 我的目标是使用多个我已经设法实现的文件压缩文件夹。 But I need to format the file names. 但是我需要格式化文件名。

Some files in the folder might contain date either as prefix or suffix of filename (example: ddmmyyyyexpense.xlsx or expenseddmmyyyy.txt ). 文件夹中的某些文件可能包含日期或者作为文件名的前缀或后缀(例如: ddmmyyyyexpense.xlsxexpenseddmmyyyy.txt )。

I would like to remove the date from the file name. 我想从文件名中删除日期。

Note: I could have any file type 注意:我可以使用任何文件类型

.xls 的.xls
.xlsx .xlsx
.csv .csv
.txt 。文本

I tried using wildcards appending to one of the strings and VBtextcompare but it didn't work. 我尝试使用附加到字符串之一和VBtextcompare通配符,但是没有用。

as I like a RegExp I will :) 我喜欢RegExp,所以我会:)

This code looks for an eight digit number, tests if this is a valid date, and if so removes it. 这段代码寻找一个八位数的数字,测试这是否是一个有效日期,如果是,则将其删除。

If you have more than one possible date, or if the 8 digits are surrounded by other numbers it will need refining. 如果您有多个可能的日期,或者8位数字被其他数字包围,则需要进行细化。

The code below feeds three sample strings to the cleaning function, it strips the date from the first and third, leaves the second as is. 下面的代码将三个示例字符串提供给清洗功能,它从第一个和第三个剥离日期,而第二个照原样。

Sub TestDate()
Debug.Print CleanStr("01142012expense.xlsx")
Debug.Print CleanStr("421142012expense.xlsx")
Debug.Print CleanStr("expense16042015.xlsx")
End Sub

code

Function CleanStr(strIn As String) As String
Dim objRegex As Object
Dim objRegMC As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
    .Pattern = "(\d{2})(\d{2})(\d{4})"
    If .test(strIn) Then
        Set objRegMC = .Execute(strIn)
        If IsDate(objRegMC(0).submatches(0) & "/" & objRegMC(0).submatches(1) & "/" & objRegMC(0).submatches(2)) Then
            CleanStr = .Replace(strIn, vbNullString)
        Else
            CleanStr = strIn
        End If
    End If
End With
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM