Path to Folder from Excel Cell Value - Power Query

ragav_in

Board Regular
Joined
Feb 13, 2006
Messages
89
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
Dear members,

Currently I am working on Power Query (very new to it), however finding my way though various help in the web. I am creating a PowerQuery that will look into all the files in a particular folder in my hard drive ("C:\Users\12345678\Desktop\Macro Test\Comparison Reports") and perform the transformation and grouping and provides me the result. Now I would like to know if there is a way by which we can have the Path location dynamic rather than hard-coding in the M-query, so that anyone can use it. Below is the query, and I want the path to the folder to be accessed from an excel cell in which the PowerQuery is bein executed. If not from excel cell, can we have it accessed from a .txt file. The intention is that the connection has to be created based on the values being provided in the excel cell and txt file and not hard coded in the M-query.

Power Query:
let
Folder.Files("C:\Users\12345678\Desktop\Macro Test\Comparison Reports"),
#"Filtered Rows" = Table.SelectRows(#"Expanded Defect", each ([Kind] = "Sheet")),
in
    #"Replaced Value"

Any help in this regard is highly appreciated and I thank everyone sincerely for their time and effort to read through this post and also to provide a solution.

Thanks,
ragav_in
 

Excel Facts

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).
Build a parameter query that will allow the user to specify the path.

Here is one approach

Hi alansidman, thanks for the suggestion. I tried to perform the steps as mentioned in the link, however I am getting some errors. I will check this on the weekend and let you know if I have ben able to achieve what I have expected for.

Thanks a lot.
ragav_in
 
Upvote 0
Hello,

I had success using a macro button. It allows to select a folder and lists the subfolders. You could alter that part. But afterwards, it makes a table of the folder details and runs the RefreshAll that looks at that sheet for that table.

Folder Power Query code:
Power Query:
let
    Source = Excel.CurrentWorkbook(){[Name="detail"]}[Content],
    #"Promoted Headers" = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
    #"Inserted Year" = Table.AddColumn(#"Promoted Headers", "Year", each Date.Year([Folder Create Date]), Int64.Type),
    #"Sorted Rows1" = Table.Sort(#"Inserted Year",{{"Year", Order.Ascending}}),
    #"Filtered Rows2" = Table.SelectRows(#"Sorted Rows1", each ([Folder Size] <> 0)),
    #"Changed Type2" = Table.TransformColumnTypes(#"Filtered Rows2",{{"Folder Path", type text}}),
    #"Added Parent Folder Path" = Table.AddColumn(#"Changed Type2", "Depth", each List.Count(List.Select(Text.ToList([Folder Path]), (listItem) => listItem="\"))),
    #"Added Custom" = Table.AddColumn(#"Added Parent Folder Path", "Parent Folder Path", each Text.BeforeDelimiter([Folder Path], "\", {0, RelativePosition.FromEnd}), type text),
    #"Added Custom1" = Table.NestedJoin(#"Added Custom",{"Parent Folder Path"},#"Added Custom",{"Folder Path"},"AddedParentFolderPath",JoinKind.LeftOuter),
    #"Expanded AddedParentFolderPath" = Table.ExpandTableColumn(#"Added Custom1", "AddedParentFolderPath", {"Index"}, {"AddedParentFolderPath.Index"}),
    #"Sorted Rows" = Table.Sort(#"Expanded AddedParentFolderPath",{{"Folder Path", Order.Ascending}}),
    #"Added Index" = Table.AddIndexColumn(#"Sorted Rows", "Index", 1, 1, Int64.Type),
    #"Grouped Rows" = Table.Group(#"Added Index", {"Depth", "AddedParentFolderPath.Index"}, {{"AllRows", each Table.Sort(_,{"Index",Order.Ascending}), type table [Folder Path=nullable text, Number of Files=number, Index=number, Depth=number, Parent Folder Path=text, AddedParentFolderPath.Index=nullable number]}}),
    #"Added Custom2" = Table.AddColumn(#"Grouped Rows", "NewTable", each Table.AddIndexColumn([AllRows],"Index.1",1,1)),
    #"Removed Other Columns1" = Table.SelectColumns(#"Added Custom2",{"NewTable"}),
    #"Expanded NewTable" = Table.ExpandTableColumn(#"Removed Other Columns1", "NewTable", {"Folder Path",  "Number of Files", "Folder Create Date", "Index", "Depth", "Parent Folder Path", "AddedParentFolderPath.Index", "Index.1"}, {"Folder Path", "Number of Files", "Folder Create Date", "Index", "Depth", "Parent Folder Path", "AddedParentFolderPath.Index", "Index.1"}),
    #"Filtered Rows3" = Table.SelectRows(#"Expanded NewTable", each ([Number of Files] <> 0)),
    #"Invoked Custom Function" = Table.AddColumn(#"Filtered Rows3", "DirContent", each DirContent([Folder Path])),
    #"Expanded DirContent" = Table.ExpandTableColumn(#"Invoked Custom Function", "DirContent", {"Name", "Date modified", "Attributes", "Folder Path"}, {"DirContent.Name", "DirContent.Date modified", "DirContent.Attributes", "DirContent.Folder Path"})
in #"Expanded DirContent"

DirContent Power Query function:

Power Query:
= (path as text) as table =>
let
Source = Folder.Contents(path),

Folders = Table.SelectRows(Source, each ([Attributes][Directory] = true)),

Step1 = Table.SelectColumns(Folders,{"Name", "Folder Path"}),
Step2 = Table.AddColumn(Step1, "DirContent", each @DirContent([Folder Path]& [Name])),
Step3 = Table.RemoveColumns(Step2,{"Folder Path", "Name"}),
Expanded = Table.ExpandTableColumn(Step3, "DirContent", {"Content", "Name", "Extension", "Date accessed", "Date modified", "Date created", "Attributes", "Folder Path"}, {"Content", "Name", "Extension", "Date accessed", "Date modified", "Date created", "Attributes", "Folder Path"}),

Files = Table.SelectRows(Source, each ([Attributes][Directory] = false)),

Result = Table.Combine({Files,Expanded})
in
Result

Macro:
VBA Code:
Sub sbListAllFolderDetails()
    
    'Disable screen update
    Application.ScreenUpdating = False
    Application.Calculation = xlManual
    
    'Variable Declaration
    Dim shtFldDetails As Worksheet
    Dim sRootFolderName As String
    
    'Browse Root Folder
    sRootFolderName = sbBrowesFolder & "\"
    
    'If path is not available, it display message and exit from the procedure
    If sRootFolderName = "\" Then
        MsgBox "Please select folder to find and list its contents.", vbInformation, "Input Required!"
        Exit Sub
    End If
    
    'Delete Sheet if it exists
    Application.DisplayAlerts = False
        On Error Resume Next
        ActiveWorkbook.Sheets("Folder Details").Delete
    Application.DisplayAlerts = True
    
    'Add new Worksheet and name it as 'Folder Details'
    With ThisWorkbook
        Set shtFldDetails = .Sheets.Add(After:=.Sheets(.Sheets.Count))
        shtFldDetails.Name = "Folder Details"
    End With
    
    'Create object for sheet name
    Set shtFldDetails = Sheets("Folder Details")
    
    'Clear Sheet
    shtFldDetails.Cells.Clear
    
    'Main Header and its Fomat
    With shtFldDetails.Range("A1")
        .Value = "Folder and SubFolder Details"
        .Font.Bold = True
        .Font.Size = 12
        .Interior.ThemeColor = xlThemeColorDark2
        .Font.Size = 14
        .HorizontalAlignment = xlCenter
    End With
    
    With shtFldDetails
        'Merge Header cells
        .Range("A1:F1").Merge
    
        'Create Headers
        .Range("A2") = "Folder Path"
        .Range("B2") = "Folder Name"
        .Range("C2") = "Number of Subfolders"
        .Range("D2") = "Number of Files"
        .Range("E2") = "Folder Size"
        .Range("F2") = "Folder Create Date"
        
        .Range("A2:F2").Font.Bold = True
    End With
    
    'Call Sub Procedure
    'List all folders & subfolders
    sbListAllFolders sRootFolderName
    
    'Enable Screen Update
    Application.Calculation = xlAutomatic
    Application.ScreenUpdating = True
    
    'Prepare workbook for Power Query and execute queries
    Folder_Details_Table
    Workbook_RefreshAll
    
End Sub

Sub sbListAllFolders(ByVal sourceFolder As String)
    
    'Variable Declaration
    Dim oFSO As Object, oSourceFolder As Object, oSubFolder As Object
    Dim iLstRow As Integer
            
    'Create object to FileSystemObject
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oSourceFolder = oFSO.GetFolder(sourceFolder)
    
    'Define Start Row
    iLstRow = Sheets("Folder Details").Cells(Sheets("Folder Details").Rows.Count, "A").End(xlUp).Row + 1
    
    'Update Folder properties to Sheet
    With Sheets("Folder Details")
        .Range("A" & iLstRow) = oSourceFolder.Path
        .Range("B" & iLstRow) = oSourceFolder.Name
        .Range("C" & iLstRow) = oSourceFolder.SubFolders.Count
        .Range("D" & iLstRow) = oSourceFolder.Files.Count
        .Range("E" & iLstRow) = oSourceFolder.Size
        .Range("F" & iLstRow) = oSourceFolder.DateCreated
    End With
        
    'Loop through all Sub folders
    For Each oSubFolder In oSourceFolder.SubFolders
        sbListAllFolders oSubFolder.Path
    Next oSubFolder
    
    'Autofit content in respective columns
    Sheets("Folder Details").Columns("B:F").AutoFit
    
    'Release Objects
    Set oSubFolder = Nothing
    Set oSourceFolder = Nothing
    Set oFSO = Nothing
    
End Sub

Public Function sbBrowesFolder()
    Dim FldrPicker As FileDialog
    Dim MyPath As String
        
    'Browse Folder Path
    Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
    
      With FldrPicker
        .Title = "Browse Root Folder Path"
        .AllowMultiSelect = False
                  If InitPath <> "" Then
            If Right$(InitPath, 1) <> "\" Then
                InitPath = InitPath & "\"
            End If
            .InitialFileName = InitPath
        Else
            .InitialFileName = "C:\"   ' <-- What can I put here to start at "This PC" ?
        End If
          If .Show <> -1 Then Exit Function
          MyPath = .SelectedItems(1)
      End With
 
      sbBrowesFolder = MyPath
      If MyPath = vbNullString Then Exit Function

End Function

Sub Folder_Details_Table()
    
    Dim LC As Long
    Dim lr As Long
    Dim ws As Worksheet
    
    Set ws = ActiveSheet
    
    LC = ws.Cells(1, Columns.Count).End(xlToLeft).Column
    lr = ws.Cells(Rows.Count, 1).End(xlUp).Row
    ws.ListObjects.Add(xlSrcRange, ws.Range(ws.Cells(1, 1), ws.Cells(lr, LC)), , xlYes).Name = "detail"
    ws.ListObjects("detail").TableStyle = "TableStyleLight8"

     
End Sub

Sub Workbook_RefreshAll()

Dim mySheet
mySheet = Sheet5.Name
Sheets(mySheet).Activate
On Error Resume Next
ActiveSheet.Rows("3:6536").Rows.Ungroup
ActiveSheet.Rows("3:6536").Rows.EntireRow.Hidden = False
Range("File_List[[Category]:[Folder, File Name and Attributes]]").ClearContents
ActiveWorkbook.RefreshAll

End Sub
 
Upvote 0
Hi alansidman, thanks for the suggestion. I tried to perform the steps as mentioned in the link, however I am getting some errors. I will check this on the weekend and let you know if I have ben able to achieve what I have expected for.

Thanks a lot.
ragav_in
Did you find a solution? I've just asked something similar. My approach is close, works initially but then it won't update. So hoped you found a solution.

My post
 
Upvote 0
Hi alansidman, thanks for the suggestion. I tried to perform the steps as mentioned in the link, however I am getting some errors. I will check this on the weekend and let you know if I have ben able to achieve what I have expected for.

Thanks a lot.
ragav_in
I solved it. If you need a guide I can guide you to a short youtube clip (if that allowed :rolleyes:), that takes you through it.
 
Upvote 0
I solved it. If you need a guide I can guide you to a short youtube clip (if that allowed :rolleyes:), that takes you through it.
Dear Want2BExcel, it would be highly appreciated if you can guide us on what was the solution and how it was achieved. I could not achieve it and still in the same stage as when I started this thread. Do keep this forum posted on how you managed to resolve it. Thanks in advance for your guidance.
 
Upvote 0
If you have your information in an excel table, and just think about having a one cell table, its a bit like having a named range containing the dynamic folder path. This Gets called called in Power Query.

There is a macro function where a user uses it to select a folder, as opposed to entering their path (e.g. from the clipboard to a cell). Unfortunately, there is no simple straightforward way to do this (i.e., load, update named range) because it requires you to know your exact specifications.. This is why there are tutorials that exist on the internet. I would watch this one:
 
Upvote 0
Dear Want2BExcel, it would be highly appreciated if you can guide us on what was the solution and how it was achieved. I could not achieve it and still in the same stage as when I started this thread. Do keep this forum posted on how you managed to resolve it. Thanks in advance for your guidance.
Here's two guides which uses a different approaches . I used the first

 
Upvote 0

Forum statistics

Threads
1,223,098
Messages
6,170,106
Members
452,302
Latest member
TaMere

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top