2011-03-02 72 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