从SQL查询将列名称拉入Excel

编程入门 行业动态 更新时间:2024-10-26 23:29:37
本文介绍了从SQL查询将列名称拉入Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Excel从SQL数据库中提取数据。我使用另一个SO问题的代码,它的工作正常。现在我想从表中拉入列名,除了实际的表。我发现我可以使用For Each fld循环得到这些名字。然而,仍然存在在Excel中一行一行地填充它们的问题,因为列数可能会改变 - 所以我认为我将需要另一个对于每个循环也可以类似的。

I'm using Excel to pull data from an SQL db. I used the code from another SO question and it works fine. Now I want to pull in the column names from a table in addition to the actual table. I figured out that I could get the names using the For Each fld loop. However there's still the issue of populating them horizontally in a row in Excel as the number of columns might change - so I'm thinking I would need another For each loop also or something similar.

Sub GetDataFromADO() 'Declare variables' Set objMyConn = New ADODB.Connection Set objMyCmd = New ADODB.Command Set objMyRecordset = New ADODB.Recordset 'Open Connection' objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;User ID=abc;Password=abc;" objMyConn.Open 'Set and Excecute SQL Command' Set objMyCmd.ActiveConnection = objMyConn objMyCmd.CommandText = "select * from myTable" objMyCmd.CommandType = adCmdText objMyCmd.Execute 'Loop Names' ' WHAT TO DO HERE????' 'Open Recordset' Set objMyRecordset.ActiveConnection = objMyConn objMyRecordset.Open objMyCmd 'Copy Data to Excel' ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset) End Sub

推荐答案

我尝试了4次尝试后,这是循环的代码。

Ok so I figured it out after 4 attempts, here's the code for the loop.

'Loop' Dim FieldRange As Range Set FieldRange = Range("A4") Set TableColumns = Range("A4:H4") x = 1 Range("A4").Select For Each fld in objMyRecordset.Fields ActiveCell.Value = fld.Name ActiveCell.Offset(0, x).Select x = x + 1 'tick iterator Next ActiveSheet.Range("A5").CopyFromRecordset objMyRecordset Range("A4").Select

更多推荐

从SQL查询将列名称拉入Excel

本文发布于:2023-10-26 08:05:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529579.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:拉入   名称   SQL   Excel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!