excel - 如何从文本文件加载 PQ 函数

标签 excel powerquery

就像在 VBA 中一样,我们可以将函数宏保存在 .xlam 文件中并将它们加载到另一个文件中。在电源查询中,我想将常用的函数存储在一个中心位置,并在必要时引用这些位置。

我知道我们可以按照this guide存储强力查询以供以后使用.

但是,此技巧不适用于函数。

假设我有一个非常简单的函数来获取 Excel 范围的值:

(RangeName as text) =>
let
  RangeValue = Excel.CurrentWorkbook(){[Name=RangeName]}[Content]{0} [Column1]
in
  RangeValue

我尝试按如下方式链接到该文件:

(RangeName as text) =>
  let
  GetFunction = Text.FromBinary(File.Contents(Excel.CurrentWorkbook(){[Name="PQMacrosFolder"]}[Content]{0}[Column1]&"RangeValue.txt")),
  EvaluateFunction = Expression.Evaluate(GetFunction, #shared)
in
  EvaluateFunction

(您会看到我正在使用函数本身的语法从 Excel 命名范围“PQMacrosFolder”获取文件夹路径。)

它表明该函数已正确加载到查询编辑器中。 enter image description here

但是当我尝试输入一些测试值并调用该函数时,它只是再次显示相同的函数屏幕。 enter image description here

最佳答案

这是从文本文件加载函数并对列执行操作的函数。该函数是从文本文件加载的,并且输入是在同一查询中设置的。这假设输入变量是在两个单独的查询中定义的(如下所示)。

请注意,如果出现 Formula.firewall 错误,您将需要将命名范围值写入同一查询中,或更改查询选项以忽略隐私设置。为了便于阅读,我更喜欢将它们分开。

let

    //Load M code from text file

    Source = Text.FromBinary(File.Contents(p_myTextFilePath)),

    //Evaluate the code from the file as an M expression
    EvaluatedExpression = Expression.Evaluate(Source, #shared),    

    //Invoke Function
    InvokeFunction = EvaluatedExpression(p_myTableName)

in

    InvokeFunction

查询以获取用作文本文件路径和表名称(如命名范围)的值。

p_myTableName 查询

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

p_myTextFilePath 查询

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

enter image description here

修订#1

下面是从文本文件加载函数的函数语法。表名称是文本文件中函数的参数,因此当您调用下面的函数时,文本文件中的函数会出现,为表规范做好准备。

(myTextFilePath) =>

let

    //Load M code from text file

    Source = Text.FromBinary(File.Contents(myTextFilePath)),

    //Evaluate the code from the file as an M expression

    EvaluatedExpression = Expression.Evaluate(Source, #shared)    

in

    EvaluatedExpression

这是上面的函数在被调用之前的屏幕截图。

enter image description here

这是调用函数后的另一个屏幕截图,准备指定下一个参数。

enter image description here

关于excel - 如何从文本文件加载 PQ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56824523/

相关文章:

powerbi - POWER BI 使用一系列列从现有查询中创建新查询

excel - Powerquery 按组运行计数

PowerQuery - 检查列值是否等于 true

c++ qt API 适用于 Excel 2010 但不适用于 excel 2013

excel - 来自 Excel Power Query 的 HDFS 连接

excel - 添加excel公式作为范围的一部分

python - 使用Python或Excel vba将单个Excel单元格内容拆分为不同的单元格

powerbi - 如何根据 Power BI 表的另一列中的唯一日期对列中的 DISTINCT 值求和

python - 表格-py ImportError : cannot import name 'read_pdf'

Ruby Roo Gem - 将 Excel xlsx 表读入哈希