Get Current Workbook Path - Excel Power Query

12,574

Solution 1

There is no direct way to do this in Power Query. If you can fill the value into a cell you can get that value through Excel.CurrentWorkbook.

Solution 2

Instead of using VBA, you can use the following method which merely involves using an Excel formula:

  1. Define the following formula in Excel and name this cell "FilePath":
=LEFT(CELL("filename",$A$1),FIND("[",CELL("filename",$A$1),1)-1)
  1. Add the following function in PowerQuery. This will return the current directory:
() =>
let
    CurrentDir = Excel.CurrentWorkbook(){[Name="FilePath"]}[Content]{0}[Column1]
in
    CurrentDir 
  1. Now you can import your CSV (or other) file from the current directory:
let
    Source = Csv.Document(File.Contents(currentdir() & "filename.csv"),[Delimiter=";", Columns=15, Encoding=65001, QuoteStyle=QuoteStyle.None])
in
    Source

Credits: https://techcommunity.microsoft.com/t5/excel/power-query-source-from-relative-paths/m-p/206150

Solution 3

You can use VBA and have a cell filled in when the file is opened during the Workbook_Open event:

Private Sub Workbook_Open()
Dim root As String

root = ActiveWorkbook.path

Range("root").Value = root
'root is the named range used in power query.
End Sub

You can then get this variable from the named range ("root") into Power Query by doing something along these lines:

let
    Source = Excel.CurrentWorkbook(){[Name="root"]}[Content][Column1]{0}
in
    Source
Share:
12,574
dfresh22
Author by

dfresh22

Work as a Python Developer specializing pipeline integrity. Working with Abaqus, Openturns, Numpy, Scipy, many others..., PYQT5. Also have >7 years developing VBA modules and classes. 3 years building C# desktop applications. Experience with GIT, SVN, TFS PyCharm community for the win. VS for all .NET I love working out, playing with my polish lowland sheepdog, golf and Seahawks

Updated on June 27, 2022

Comments

  • dfresh22
    dfresh22 almost 2 years

    Trying to add a custom column and populating the value with the current workbook path name.

    I have tried Excel.Workbook.name and Excel.CurrentWorkbook() and other objects, but it seems those are limited to pulling data.

    in VBA this is simply WorkbookObject Path property. but with power query its another story. The references and libraries on Microsoft site are limited for power query.

    https://msdn.microsoft.com/en-us/library/mt779182.aspx

  • dfresh22
    dfresh22 about 7 years
    Yea I figured as much. not the most elegant but with some post processing I do the following. ListObject.DataBodyRange.Columns(3).Formula = "=""" & WorkbookObject.FullName & """"