简体   繁体   English

获取当前工作簿路径 - Excel Power Query

[英]Get Current Workbook Path - Excel Power Query

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.我尝试过 Excel.Workbook.name 和 Excel.CurrentWorkbook() 和其他对象,但似乎这些仅限于提取数据。

in VBA this is simply WorkbookObject Path property.在 VBA 中,这只是 WorkbookObject Path 属性。 but with power query its another story.但随着权力的质疑,它又是另一回事了。 The references and libraries on Microsoft site are limited for power query. Microsoft 站点上的参考和库仅限于电源查询。

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

Instead of using VBA, you can use the following method which merely involves using an Excel formula:您可以使用以下仅涉及使用 Excel 公式的方法,而不是使用 VBA:

  1. Define the following formula in Excel and name this cell "FilePath":在 Excel 中定义以下公式并将此单元格命名为“FilePath”:
=LEFT(CELL("filename",$A$1),FIND("[",CELL("filename",$A$1),1)-1)
  1. Add the following function in PowerQuery.在 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:现在您可以从当前目录导入您的 CSV(或其他)文件:
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/mp/206150学分: https : //techcommunity.microsoft.com/t5/excel/power-query-source-from-relative-paths/mp/206150

There is no direct way to do this in Power Query.在 Power Query 中没有直接的方法可以做到这一点。 If you can fill the value into a cell you can get that value through Excel.CurrentWorkbook .如果您可以将该值填充到单元格中,则可以通过Excel.CurrentWorkbook获取该值。

You can use VBA and have a cell filled in when the file is opened during the Workbook_Open event:您可以使用 VBA 并在 Workbook_Open 事件期间打开文件时填充单元格:

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:然后,您可以通过执行以下操作,将该变量从命名范围(“root”)中获取到 Power Query 中:

let
    Source = Excel.CurrentWorkbook(){[Name="root"]}[Content][Column1]{0}
in
    Source

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM