Excel宏只读取今天创建的文件的输入

时间:2012-08-17 18:02:55

标签: excel vba excel-vba

我有一个以txt格式导出每日报告的应用程序。 我有一个宏从这些报告中提取某些数据行,并将它们放在输出xls文件中。我的宏的输入目录是一个单独的文件夹,我手动将今天的报告移动到。

我希望我的宏能够只读取默认的报告文件夹,只读取用今天的日期创建的文件。

报告文件的命名约定如下: 1101_16_16_AppServiceUser_YYYYMMDDhhmmssXXX.txt 不确定文件名的最后3位代表什么,但它们总是数字。

帮助?

哇快!谢谢...第一次使用stackoverflow。 我想我应该包含拉取数据并将其转储到excel的代码...这里是:

Sub PullLinesFromEPremisReport()
Dim FileName, PathN, InputLn As String
Dim SearchFor1, SearchFor2, OutpFile As String
Dim StringLen1, StringLen2 As Integer
Dim colFiles As New Collection
Dim bridgekey As String

PathO = "C:\Documents and Settings\GROMERO\Desktop\CM reconciliation\output\"
PathN = "C:\Documents and Settings\GROMERO\Desktop\CM reconciliation\input\"

FileName = Dir(PathN)

While FileName <> ""
    colFiles.Add (FileName)
    FileName = Dir

Wend

SearchFor1 = "BRIDGE KEY"

StringLen1 = Len(SearchFor1)


OutpFile = "RESULTS.xls"
Open PathO & OutpFile For Output As #2

For Each Item In colFiles
    Open PathN & Item For Input As #1
        Do Until EOF(1) = True
               Line Input #1, InputLn
               If (Left(LTrim$(InputLn), StringLen1) = SearchFor1) Then
                    bridgekey = InputLn
           End If

    Loop

Close #1
Next Item

Close #2
End Sub

3 个答案:

答案 0 :(得分:2)

你可以通过两种方式做到这一点。假设您通过File使用FileSystemObject

Instr上的file.Name在字符串中查找Format(Date, "YYYYMMDD")

或者使用更简单的方法循环遍历文件并在循环中执行此操作:

If File.DateCreate >= Date Then
    'Do something
end if

其中File是用于循环遍历文件的实际变量。

答案 1 :(得分:2)

Daniel的回答是正确的,但使用FileSystemObject需要几个步骤:

确保您引用了“Microsoft Scripting Runtime”: enter image description here enter image description here

然后,遍历目录中的文件:

Sub WorkOnTodaysReports()

'the vars you'll need
Dim fso As New FileSystemObject
Dim fldr As Folder
Dim fls As Files
Dim fl As File

Set fldr = fso.GetFolder("C:\Reports")
Set fls = fldr.Files

For Each fl In fls

    'InStr returns the position of the substring, or 0 if not found
    '    EDIT: you can explicitly use the reliable parts of your file name
    '    to avoid false positives
    If InStr(1, fl.Name, "AppServiceUser_" & Format(Now, "YYYYMMDD")) > 0 Then

        'Do your processing

    End If

Next fl

End Sub

编辑:所以我,您发布的代码可以按照您的意愿将PathN发送到主Reports文件夹,然后只修改您的While语句这样:

While FileName <> ""

    If InStr(1, FileName, "AppServiceUser_" & Format(Now, "YYYYMMDD")) > 0 Then

        colFiles.Add (FileName)

    End If

    FileName = Dir

Wend

答案 2 :(得分:1)

If fileName like "*AppServiceUser_" & Format(Now, "YYYYMMDD") & _
                                              "#########.txt" Then
    'good to go
End If