2014-03-28 63 views
0

有人可以告訴我,如果用戶可以在輸入框中輸入兩個單獨的日期,然後在文件夾中搜索具有(理想情況下)創建落入輸入日期之間的日期的文件?如何在兩個日期之間搜索文件?

我可以通過文件夾中的文件進行搜索,但文件數量每天都在增加,並且運行搜索所需的時間越來越長。我希望如果用戶可以選擇日期範圍,那麼這將減少運行時間。

如果這是不可能的,可以設置一個宏來搜索文件夾中的文件從最近創建的文件開始搜索,然後從那裏開始工作?

Sub UKSearch() 

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
'Search function to find specific consignment number from multiple intake sheets' 
'Used by Traffic Office               ' 
'Created by *********** 11/03/14  Password to unlock = *********    ' 
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 

Dim FSO As Object 'FileSystemObject 
Set FSO = CreateObject("scripting.filesystemobject") 
Dim Directory As String 
Dim FileName As String 
Dim varCellvalue As Long 

Application.ScreenUpdating = False 
MsgBox ("This may take a few minutes") 

'value to be searched 
varCellvalue = Range("D13").Value 

'Change the directory below as needed 
Directory = "\\*******\shared$\Common\Returns\*********\" 
If Right(Directory, 1) <> "\" Then 
    Directory = Directory & "\" 
End If 

'Search for all files in the directory with an xls* file type. 
FileName = Dir(Directory & "*.xls*") 

'''''''''''''''''''''''' 
'Opens, searches through and closes each file 
Do While FileName <> "" 
OpenFile = Directory & FileName 
Workbooks.Open (OpenFile) 

Workbooks(FileName).Activate 

'Count through all the rows looking for the required number 
ActiveWorkbook.Sheets("UK Scan Sheet").Activate 
LastRow = Range("B65536").End(xlUp).Row 

intRowCount = LastRow 

Range("B1").Select 

For i = 1 To intRowCount 
    'If the required number is found then select it and stop the search 
    If ActiveCell.Value = varCellvalue Then 
     GoTo Finish 
     Else 
    End If 
ActiveCell.Offset(1, 0).Select 
Next i 

Workbooks(FileName).Close 
FileName = Dir 
OpenFile = "" 
Loop 
'''''''''''''''''''''''''' 

Finish: 

Application.ScreenUpdating = False 

End Sub 
+0

我不確定你的目標是什麼,但如果你想獲得日期過濾的文件名集合,你可能會從[本視頻]中獲得一些靈感(http://www.teachexcel.com/excel -tutorials/N-1566,VBA的提示---列表檔案-IN-A-Folder.html)? –

+0

你可以看看如何確定創建日期這個答案:http://stackoverflow.com/questions/18660818/excel-vba-pdf-file-properties/18661886#18661886。嘗試將它合併到您的代碼中,如果您遇到困難,請回復並且我們會爲您提供幫助 –

+0

我會盡量做得更清楚: - 我想要做的是 - 用戶按下命令按鈕 - 輸入框日期(YYYY-MM-DD) - 第二日期的輸入框(YYYY-MM-DD) - 搜索值的輸入框 - 宏在兩個輸入日期之間的文件夾中查找第一個文件 - 宏搜索該文件中的搜索值 - 如果未找到,則移動到下一個文件,直到到達兩個輸入日期之間的最後一個文件。 我希望能讓我更清楚自己想做什麼? – LuckySevens

回答

1

添加到您的昏暗區段:

Dim oFile 

你的循環加載之前:

Set oFile = CreateObject("Scripting.FileSystemObject") 

在循環打開文件中添加一個if語句之前:

if oFile.getFile(Directory & FileName).DateCreated >= EarliestDate and oFile.getFile(Directory & FileName).DateCreated <= LatestDate 

您也可以使用oFile.getFile(目錄& FileName).DateLastModified - 如果您想使用文件的上次更改日期而不是創建日期。

相關問題