Sub PullDatafomClosedWBV2()
'
' This macro will get the first alphabetical sheet name from a closed xlsx workbook and then get data from that sheet name.
' It works with numbers, spaces and ' Workbook remains closed the entire time.
'
' Apostrophe in file name is now handled :)
'
'
' Turn Settings off
Application.ScreenUpdating = False ' Turn Screen Updating off
Application.Calculation = xlCalculationManual ' Turn AutoCalculation off
Application.EnableEvents = False ' Turn EnableEvents off
'
Dim DestinationSheetName As String, SourceDirectory As String, SourcefileName As String, SourceSheetName As String
Dim DestinationRow As Long
Dim conexion As Object, objCat As Object
'
DestinationSheetName = "Unit_Data" ' <--- Set this to the Destination Sheet Name
DestinationRow = 1 ' <--- Set this to the top row for the results
SourceDirectory = ActiveWorkbook.Path & "\Orders\" ' <--- Set this to the folder name that contains the source files
SourcefileName = Dir(SourceDirectory & "*.xlsx") ' Save source file name
'
Set conexion = CreateObject("adodb.connection")
Set objCat = CreateObject("ADOX.Catalog")
'
Do While SourcefileName <> ""
DestinationRow = DestinationRow + 1
'
conexion.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & SourceDirectory & SourcefileName & "; Extended Properties=""Excel 12.0; HDR=YES"";"
'
Set objCat.ActiveConnection = conexion
SourceSheetName = Replace(objCat.Tables(0).Name, "$", "")
SourceSheetName = Replace(SourceSheetName, "'", "")
conexion.Close
'
SourcefileName = Replace(SourcefileName, "'", "''") ' replace any apostrophe in file name with a double apostrophe
'
With ThisWorkbook.Sheets(DestinationSheetName).Range("A" & DestinationRow & ":H" & DestinationRow)
.Formula = Array( _
"='" & SourceDirectory & "[" & SourcefileName & "]" & SourceSheetName & "'!G25", _
"='" & SourceDirectory & "[" & SourcefileName & "]" & SourceSheetName & "'!G26", _
"='" & SourceDirectory & "[" & SourcefileName & "]" & SourceSheetName & "'!G27", _
"='" & SourceDirectory & "[" & SourcefileName & "]" & SourceSheetName & "'!G28", _
"='" & SourceDirectory & "[" & SourcefileName & "]" & SourceSheetName & "'!G34", _
"='" & SourceDirectory & "[" & SourcefileName & "]" & SourceSheetName & "'!G35", _
"='" & SourceDirectory & "[" & SourcefileName & "]" & SourceSheetName & "'!G36", _
"='" & SourceDirectory & "[" & SourcefileName & "]" & SourceSheetName & "'!G39")
.Value = .Value ' Remove formulas from range, leave just the resulting values
End With
'
SourcefileName = Dir
Loop
'
Set objCat = Nothing
Set conexion = Nothing
'
' Turn Settings back on
Application.EnableEvents = True ' Turn EnableEvents back on
Application.Calculation = xlCalculationAutomatic ' Turn AutoCalculation back on
Application.ScreenUpdating = True ' Turn Screen Updating back on
End Sub