简体   繁体   English

如何使用 VBA 编辑电源查询的来源?

[英]How to edit the source of a power query using VBA?

I am trying to edit the source of one of my queries using VBA.我正在尝试使用 VBA 编辑我的一个查询的来源。 This is what I have so far:这是我到目前为止:

 Dim mFormula As String

 mFormula = _

 "let Source = Excel.Workbook(File.Contents(wbname), null, true) in Source"

 query1 = ActiveWorkbook.Queries.Add("LATEST", mFormula)

I set wbname previously in my code.我之前在代码中设置了wbname "LATEST" is already added, instead of delete it and read it, I would just like to change the source. “最新”已添加,与其删除并阅读它,我只想更改来源。 Is this possible?这可能吗?

You can use ActiveWorkbook.Queries.Item to get the query you want and use the Formula property to update the query's formula, like so:您可以使用ActiveWorkbook.Queries.Item来获取您想要的查询并使用Formula属性来更新查询的公式,如下所示:

ActiveWorkbook.Queries.Item("LATEST").Formula = "let MyNewFormula = 1 + 1 in Source"

Note: this only works on Excel 2016 or later.注意:这仅适用于 Excel 2016 或更高版本。

I beleive you'd better avoid such methods as they can cause compatibility problems as well as some other.我相信您最好避免使用此类方法,因为它们会导致兼容性问题以及其他一些问题。

If you learn M, you probably won't need to edit code with VBA.如果您学习 M,您可能不需要使用 VBA 编辑代码。

A bit late to the party, but additionally, for anyone who views this moving forward one can use:聚会有点晚了,但另外,对于任何看到这一进展的人,都可以使用:

Thisworkbook.Queries("LATEST").Formula = mFormula

Note, ThisWorkbook is preferable to ActiveWorkbook .请注意, ThisWorkbook优于ActiveWorkbook

It is not recommended to use Thisworkbook.Queries(index).Formula = "newFormula" to change your queries, but I have not discovered any other method to update the connections.不建议使用 Thisworkbook.Queries(index).Formula = "newFormula" 来更改您的查询,但我还没有发现任何其他方法来更新连接。

The drawback working with this method is that you can not change any specific property of the connection (source, etc), but you can use the functions Split, Replace, Instr, Mid, etc to get exactly what you want.使用此方法的缺点是您无法更改连接的任何特定属性(源等),但您可以使用 Split、Replace、Instr、Mid 等函数来准确获得您想要的内容。

Another drawback is that so often the new ".formula" throws syntax errors.另一个缺点是新的“.formula”经常抛出语法错误。 For that, you will need a simple error handler.为此,您将需要一个简单的错误处理程序。

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

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