如何“按列sorting”和“包含查询列名”?

我想在Excel中运行一个SQL查询,我想:

1.通过我的列“Stationname”命令查询结果
2.在查询中包含列名

现在它将返回没有列名称的所有列,最终用户不知道它是什么。

有人可以帮忙吗? 我卡住了! 以下是我目前的代码:

strQuery = "select pipelineflow.lciid lciid, ldate, volume, capacity, status, " & _ "pipeline, station, stationname, drn, state, county, owneroperator, companycode, " & _ "pointcode, pointtypeind, flowdirection, pointname, facilitytype, pointlocator, " & _ "pidgridcode from pipelineflow, pipelineproperties " & _ "where pipelineflow.lciid = pipelineproperties.lciid " & _ "and pipelineflow.audit_active = 1 " & _ "and pipelineproperties.audit_active =1 " & _ "and pipelineflow.ldate " & dtInDate & _ "and pipelineproperties.stationname = '" & Stationname & "' " 

对于您的问题的第一部分,添加一个ORDER BY子句到您的查询。 在这种情况下: 按站名命令

第2部分:不确定为什么列名不包含在查询中。 您可以使用类似下面的内容(纯粹是一个示例)明确命名列:

 select mycolumn as "MyCustomizedColumnName" from mytable 

这允许你给你select的列名称。 话虽如此,你不应该被要求为每一个栏目这样做,所以我怀疑你的情况正在发生其他事情。


我应该补充一点,存储过程(而不是dynamicSQL)将产生更好的运行时性能。

只需要订购

 Order By stationname 

在查询结束。

您可以通过使用以下代码遍历列名称:

 rst(1).Name 

其中第一个是您的logging集,并且该数字是列的索引。

要对查询结果进行sorting,请在查询结尾处使用“ORDER BY” 。 你的查询的最后一行看起来像这样

 "and pipelineproperties.stationname = '" & Stationname & "' " & _ "ORDER BY pipelineproperties.stationname" 

列标题将返回您的查询数据,但不会自动写入到Excel工作表。 下面的代码片段展示了如何遍历logging集的列标题,并将它们写入活动单元格的行。

“第一个”是指您的logging集,根据需要更新名称。

 If Not rst.EOF Then For x = 0 To rst.Fields.Count - 1 With ActiveCell.Offset(0, lcount) .Value = rst.Fields(x).Name End With Next End If 

在将查询结果写入工作表时,请确保从活动单元格向下偏移,否则标题将被数据覆盖。

 Activecell.Offset(1,0).CopyFromRecordset rst