从 SQL 查询将列名称提取到 Excel 中
我正在使用 Excel 从 SQL 数据库中提取数据。我使用了另一个问题中的代码,效果很好。现在,除了实际表之外,我还想从表中提取列名。我发现我可以使用 For Each fld 循环获取名称。然而,在 Excel 中水平填充它们仍然存在问题,因为列数可能会改变 - 所以我想我还需要另一个 For every 循环或类似的东西。
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我通常的代码非常相似:
My usual code is very similar:
好的,我在尝试了 4 次后才弄清楚,这是循环的代码。
Ok so I figured it out after 4 attempts, here's the code for the loop.
为了使其变得超级简单,请执行以下操作(使用 Sheet1 和记录集 r)
To make it super simple, do something like this (using Sheet1 and recordset r)
您可以将“x”变量设置为 0,然后执行以下操作:
这将使阅读变得更容易...:)
You can just set your "x" variable to 0 and then do something like:
And that will make it a bit easier to read... :)