2011-03-02 66 views
0

我想在Excel中使用宏导入最后修改的txt文件。 我有一个每天增加一个新的txt文件的文件夹。 目标是导入添加到目录中的最后一个txt文件。使用Excel导入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 

谢谢

回答

1

一种方式做到这一点是使用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 

你可以看到所有的代码,你需要在这里

http://www.dailydoseofexcel.com/archives/2009/05/01/opening-the-newest-file-in-a-folder-with-vba/

0

设置,我发现从另一个线程这个例子中,引用但它只在文件名总是相同的情况下才起作用。 这一个检查与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