首先呢,得获取所有文件名称,然后呢,根据文件名称年月日部分挑出最新日期,再然后呢,根据最新日期生成文件名,再然后呢,进行复制。
注:你的源数据文件名和目录结构应该如图
样本文件见附件
代码如下
Sub test()
Dim pth As String, fn As String, ary(), tmpMax As Long, i As Integer
Dim wb As Workbook
pth = "D:\data\" '设置路径
fn = Dir(pth & "*.xlsx") '遍历该路径下的.xlsx文件
i = 0: tmpMax = 0
Do While fn <> ""
If fn <> ThisWorkbook.Name Then
i = i + 1
ReDim Preserve ary(i) '声明动态数组,在数组后面追加元素
ary(i) = --Left(Right(fn, 13), 8) '假设文件名称形式为“namelist20140918.xlsx”这样的格式,将年月日8位数装入数组
If ary(i) > tmpMax Then tmpMax = ary(i) '不断将找到的最大日期值放入变量tmpmax
End If
fn = Dir
Loop
Set wb = Workbooks.Open(pth & "namelist" & tmpMax & ".xlsx", , True) '打开tmpmax指定的文件
wb.Worksheets("Sheet2").Cells.Copy ThisWorkbook.Worksheets("Sheet3").Cells '复制目标相关内容
wb.Close
End Sub