[英]Excel VBA: Combine multiple workbooks into one workbook
我使用以下腳本將多個工作簿(僅工作表1)復制到一個主工作簿中。 但是,由於每天要在源文件夾中保存多個文件,因此我現在在源文件夾中有數百個文件,並且希望優化復制到主文件的文件夾。
我有一種通過使用文件名中顯示的日期來限制文件夾的方法。 文件路徑總是相同的格式...
5個字母字符__文件保存的日期(日期格式:ddmmyy)__朱利安日期
例如
NOCSR__060715__162959
SBITT__060715__153902
LVECI__030715__091316
我可以在文件路徑中使用日期,並允許用戶輸入“開始”和“結束”日期嗎? 然后,主工作簿將僅從日期范圍內保存的文件中提取數據。
Sub MergeFilesWithoutSpaces()
Dim path As String, ThisWB As String, lngFilecounter As Long
Dim wbDest As Workbook, shtDest As Worksheet, ws As Worksheet
Dim Filename As String, Wkb As Workbook
Dim CopyRng As Range, Dest As Range
Dim RowofCopySheet As Integer
ThisWB = ActiveWorkbook.Name
path = "K:\UKSW CS Bom Expections\CS_BOM_Corrections\Archive"
RowofCopySheet = 2
Application.EnableEvents = False
Application.ScreenUpdating = False
Set shtDest = ActiveWorkbook.Sheets(1)
Filename = Dir(path & "\*.xls", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = vbNullString
If Not Filename = ThisWB Then
Set Wkb = Workbooks.Open(Filename:=path & "\" & Filename)
Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(Cells(Rows.Count, 1).End(xlUp).Row, Cells(1, Columns.Count).End(xlToLeft).Column))
Set Dest = shtDest.Range("A" & shtDest.Cells(Rows.Count, 1).End(xlUp).Row + 1)
CopyRng.Copy
Dest.PasteSpecial xlPasteFormats
Dest.PasteSpecial xlPasteValuesAndNumberFormats
Application.CutCopyMode = False 'Clear Clipboard
Wkb.Close False
End If
Filename = Dir()
Loop
謝謝,SMORF
我不確定您是否需要將日期保存在文件名中。 您可以使用此功能讀取文件的創建日期屬性...
Sub GetDateCreated()
Dim oFS As Object
Dim strFilename As String
'Put your filename here
strFilename = "c:\excel stuff\commandbar info.xls"
'This creates an instance of the MS Scripting Runtime FileSystemObject class
Set oFS = CreateObject("Scripting.FileSystemObject")
MsgBox strFilename & " was created on " & oFS.GetFile(strFilename).DateCreated
Set oFS = Nothing
End Sub
然后,您可以編寫一個具有開始日期和結束日期並返回文件名列表的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.