Hello m
Here's a try (amend sheet name and path)
(please note that workbook containing code should NOT be in same directory
as files searched)
Option Base 1
Sub Consolider()
With Application.FileSearch
..NewSearch
..LookIn = "C:\DOC\Robi10\Doc\Excel\Tests\MPFE"
..FileType = msoFileTypeExcelWorkbooks
If .Execute() <> 0 Then
Dim Part1, Part2, SourceFile$, n&, AntiSlashPos&, FileNamesArray()
For i = 1 To .FoundFiles.Count
'Define array bounds
ReDim Preserve FileNamesArray(1 To .FoundFiles.Count)
'Now build the correct syntax to consolidate:
n = Len(.FoundFiles(i)) - Len(Replace(.FoundFiles(i), "\", ""))
AntiSlashPos = Position(.FoundFiles(i), n)
'Part1 = full path
Part1 = Mid(.FoundFiles(i), 1, AntiSlashPos)
'Part2 = filename only
Part2 = Mid(.FoundFiles(i), AntiSlashPos + 1, Len(.FoundFiles(i)) -
AntiSlashPos)
SourceFile = "'" & Part1 & "[" & Part2 & "]Feuil1'!R1c1"
FileNamesArray(i) = SourceFile
'End If
Next i
ThisWorkbook.Sheets("Feuil1").Range("A1").Consolidate Sources:= _
Array(FileNamesArray()), Function:=xlSum, _
TopRow:=False, LeftColumn:=False, CreateLinks:=True
End If
End With
End Sub
'returns position of Antislash from a path info
Function Position(Chemin$, Nb&) As Long
Dim Pos1 As Long
Dim Pos2 As Long
Dim i As Long
Pos2 = 0
For i = 1 To Nb
Pos1 = Pos2
Pos2 = InStr(Pos1 + 1, Chemin, "\")
If Pos2 = 0 Then Exit For
Next i
If Pos2 > Pos1 Then
Position = Pos2
Else
Position = 0
End If
End Function
HTH
Cordially
Pascal