使用Excel使用宏导入txt?

使用Excel使用宏导入txt?,excel,Excel,我希望使用Excel中的宏从目录导入最后修改的txt文件。 我有一个文件夹,每天增加一个新的txt文件。 目标是导入目录中添加的最后一个txt文件 我已经创建了一个Excel文件,其中有一个受宏影响的按钮 以下是宏的代码: Sub Import() ' ' Import Macro ' Macro saved on 02/03/2011 by StYellowknife3000 ' ' With ActiveSheet.QueryTables.Add(Connection:= _

我希望使用Excel中的宏从目录导入最后修改的txt文件。 我有一个文件夹,每天增加一个新的txt文件。 目标是导入目录中添加的最后一个txt文件

我已经创建了一个Excel文件,其中有一个受宏影响的按钮

以下是宏的代码:

Sub Import()
'
' Import Macro
' Macro saved on 02/03/2011 by StYellowknife3000
'

'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Folder\File_01.txt", Destination:= _
        Range("A1"))
        .Name = "File_01"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 932
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = True
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = True
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

谢谢

一种方法是使用Scripting.FileSystemObject并循环检查所有文件的日期。下面是我用来打开文件夹中最新CSV的一些代码

For Each fsoFile In fsoFldr.Files
    If fsoFile.DateCreated > dtNew And fsoFile.Type = sCSVTYPE Then
        sNew = fsoFile.Path
        dtNew = fsoFile.DateCreated
    End If
Next fsoFile

Workbooks.Open sNew
您可以在这里看到需要设置的所有代码和引用


我从另一个线程中找到了这个示例,但只有当文件名始终相同时,它才起作用。 这一个用lastmodified检查文件,但它没有按我想要的那样工作

代码:

Sub test()
MsgBox FileLastModified("C:\My Documents\abook.xls")
End Sub

Function FileLastModified(strFullFileName As String)
Dim fs As Object, f As Object, s As String

Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(strFullFileName)

s = UCase(strFullFileName) & vbCrLf
s = s & "Last Modified: " & f.DateLastModified
FileLastModified = s

Set fs = Nothing: Set f = Nothing

End Function