Excel VBA:用于检查文件名称的VBA正则表达式?

时间:2013-11-15 15:40:18

标签: regex excel vba excel-vba

所以基本上我编写所有这些VBA宏来按摩大量数据。在此之前,用户应该能够输入日期并检索他们想要按摩的数据。需要按摩的数据是每天生成的Excel报告。

文件名的格式为:“Year_Month_Day_(RandomlyGeneratedNumbers)_ReportWorkSheet.xls”

我可以通过哪种方式确定文件名?我已经完成了输入日期和格式化的简单部分。数字似乎只有六位数,但我觉得它可能会改变。我当时想到可能会找到我正在寻找xls文件的目录,并使用正则表达式来匹配我已经格式化的日期以确定我需要哪个xls文件。有可能这样做吗?还是一个不同的解决方案?

仅供参考,这是我到目前为止的代码:

Dim CurrentDateString As String
Dim MonthString As String
Dim DayString As String
Dim YearString As String
Dim FileNameString As String
Dim i As Integer




CurrentDateString = Worksheets("Sheet1").Range("B2:B2").Value

'Checks to see if the date is in the proper format
If Len(CurrentDateString) = 10 Then


i = InStr(1, CurrentDateString, "/")

MonthString = Mid(CurrentDateString, 1, (i - 1))

i = InStr(4, CurrentDateString, "/")

DayString = Mid(CurrentDateString, 4, (i - 4))
i = InStr(4, CurrentDateString, "/")

YearString = Mid(CurrentDateString, 7, i)

FileNameString = YearString & "_" & MonthString & "_" & DayString & "_" &         "ThisIsWhereTheNumberWouldGo" & "ReportWorkSheet.xls"

 Else
    MsgBox "Current date must have two digits for month and year. Even if its a single digit. For      example January 1st 2014 would be 01/01/2014 NOT 1/1/2014"

  End If

1 个答案:

答案 0 :(得分:0)

对不起有任何困惑,但我能弄清楚。不需要正则表达式。我想我不清楚。基本上我需要根据输入的日期找到文件名。文件名中间的数字让我失望,但我甚至不需要在我的解决方案中考虑到这一点。我找到了一种遍历目录然后通过每个文件进行Eached的方法,并将文件的一部分与日期分开,如果有匹配的话。我在excel中打开它。很抱歉浪费任何时间:(

 FileNameString = YearString & "_" & MonthString & "_" & DayString
Set MyObject = CreateObject("Scripting.FileSystemObject")
 Set mySource = MyObject.GetFolder("J:\credit\Christopher Smith\Allegro 8.0 Reports\Post Live")

 For Each myFile In mySource.Files
      DirectoryFileNameString = myFile.Name
   DirectoryFileNameStringTemp = Mid(DirectoryFileNameString, 1, 10)
   If FileNameString = DirectoryFileNameStringTemp Then
         MsgBox "IT WORKS Filename String: " & FileNameString & " = DirectoryFilename: " & 
      Workbooks.Open (myFile.Path)
        'Call another sub to massage data here
 DirectoryFileNameStringTemp
End If
Next