如何格式化文件名中第 2 和第 4 下划线之间的值?



>我有VBA代码将文件名捕获到MS Access数据库中的表中。

这些值如下所示:

FileName
----------------------------------------------------    
WC1603992365_Michael_Cert_03-19-2019_858680723.csv
WC1603992365_John_Non-Cert_03-19-2019_858680722.csv
WC1703611403_Paul_Cert_03-27-2019_858679288.csv

每个文件名有 4 个_下划线,文件名的长度各不相同。

我想捕获第 2个和第3 个下划线之间的值,例如:

Cert
Non-Cert
Cert

我有另一个文件下载程序,它具有带有正则表达式的"重命名"功能。我设置了以下内容:

Source file Name: (.*)_(.*)_(.*)_(.*)_-(.*).(.*)
New File Name: 5.6

在此示例中,我将文件名的第 5 部分移到前面,并添加文件扩展名。

例如,WC1603992365_Michael_Cert_03-19-2019_858680723.csv将另存为文件夹中的858680723.csv

有没有办法使用 RegEx 捕获文件名的第 3 部分,并将值保存在字段中?

我尝试了VBA代码,并搜索了SQL示例,但没有找到任何示例。

因为文件名长度不是固定的,所以我不能使用LEFTRIGHT...

提前谢谢你。

一种可能的解决方案是使用 VBASplit函数将字符串拆分为字符串数组,使用下划线作为分隔符,然后返回此数组中索引 2 处的项目。

例如,您可以定义驻留在公共模块中的 VBA 函数,如下所示:

Function StringElement(strStr, intIdx As Integer) As String
Dim strArr() As String
strArr = Split(Nz(strStr, ""), "_")
If intIdx <= UBound(strArr) Then StringElement = strArr(intIdx)
End Function

在这里,我将参数strStr定义为 VariantNull以便您可以错误地传递它的值。

如果提供Null值,或者提供的索引超出了通过使用下划线拆分字符串返回的数组的边界,则该函数将返回一个空字符串。

然后,您可以从 SQL 语句调用上述函数:

select StringElement(t.Filename, 2) from Filenames t

在这里,我假设您的表称为Filenames- 更改此表以适合。

这是我完成的工作代码。感谢您分享您的答案。

Public Function getSourceFiles()
Dim rs As Recordset
Dim strFile As String
Dim strPath As String
Dim newFileName As String
Dim FirstFileName As String
Dim newPathFileName As String
Dim RecSeq1 As Integer
Dim RecSeq2 As Integer
Dim FileName2 As String
Dim WrdArrat() As String
RecSeq1 = 0

Set rs = CurrentDb.OpenRecordset("tcsvFileNames", dbOpenDynaset) 'open a recordset
strPath = "c:inRegEx"
strFile = Dir(strPath, vbNormal)

Do 'Loop through the balance of files
RecSeq1 = RecSeq1 + 1
If strFile = "" Then 'If no file, exit function
GoTo ExitHere
End If

FirstFileName = strPath & strFile
newFileName = strFile
newPathFileName = strPath & newFileName
FileName2 = strFile
Dim SubStrings() As String
SubStrings = Split(FileName2, "_")
Debug.Print SubStrings(2)
rs.AddNew
rs!FileName = strFile
rs!FileName68 = newFileName 'assign new files name max 68 characters
rs!Decision = SubStrings(2) 'extract the value after the 3rd underscore, and add it to Decision Field
rs.Update
Name FirstFileName As newPathFileName
strFile = Dir()

Loop
ExitHere:
Set rs = Nothing
MsgBox ("Directory list is complete.")
End Function

最新更新