vba 从查询表中获取列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17972352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 22:30:22  来源:igfitidea点击:

Get Column name from a query table

vbaaccess-vba

提问by user_C

With normal tables, I can access the column name using the

对于普通表,我可以使用

SELECT column_name FROM INFORMATION_SCHEMA_COLUMNS WHERE table_name = '" & Tbl & "' "

and it works...

它有效......

but during the execution of VBA code I also need to retrieve columns name not from tables, but from the table resulting after a query, how can I get that in VBA?

但是在执行 VBA 代码期间,我还需要不从表中检索列名,而是从查询后生成的表中检索列名,如何在 VBA 中获取它?

Dim Qry as QueryDef
Dim MrgTbls as QueryDef
Dim T1 as String
Dim T2 as String
Dim SQLJoin as String

...

...

Set MrgTbls = CurrentDb.CreateQueryDef(Qry.Name, SQLJoin)

... and later on I want create a query such as

...后来我想创建一个查询,如

SELECT column_name FROM INFORMATION_SCHEMA_COLUMNS WHERE table_name = 'MrgT' 

which returns nothing since the table MrgT is not in INFORMATION_SCHEMA_COLUMNS, unlike other tables.

它不返回任何内容,因为表 MrgT 不在 INFORMATION_SCHEMA_COLUMNS 中,与其他表不同。

采纳答案by Zev Spitz

To get the column names from a QueryDef, you can use the Fieldscollection:

要从 a 获取列名QueryDef,您可以使用Fields集合:

Dim firstColumnName As String
firstColumnName = MrgTbls.Fields(0).Name

Alternatively you can use pure SQL and the MSysObjectsand MSysQueriessystem tables. See herefor details about the structure of this table.

或者,您可以使用纯 SQLMSysObjectsMSysQueries系统表。有关此表结构的详细信息,请参见此处