excel 2010 vba mssql help:无法获取表头(别名)

下面是我的代码,它工作正常,但我有一个小问题。

我有两张不同的纸张:第一张纸上有一个button来获取数据。 这是工作,我可以看到第二张表中的数据。 但问题是获取表头。 我的代码无法检索标题。

Sub Add_Results_Of_ADO_Recordset() 'This was set up using Microsoft ActiveX Data Components version 2.8 Dim cnt As ADODB.Connection Dim rst As ADODB.Recordset Dim stSQL As String Dim wbBook As Workbook Dim wsSheet As Worksheet Dim rnStart As Range Const stADO As String = "PROVIDER=SQLOLEDB.1;SERVER=192.168.0.300;UID=sa;PWD=sa;DATABASE=sa" 'where BI is SQL Database & AURDWDEV01 is SQL Server Set wbBook = ActiveWorkbook Set wsSheet = wbBook.Worksheets(1) With wsSheet Set rnStart = .Range("A1") End With stSQL = "SELECT sModel,sKodu,sAciklama FROM tbstok " Set cnt = New ADODB.Connection With cnt .CursorLocation = adUseClient .Open stADO .CommandTimeout = 0 Set rst = .Execute(stSQL) End With 'Here we add the Recordset to the sheet from A1 rnStart.CopyFromRecordset rst 'Cleaning up. rst.Close cnt.Close Set rst = Nothing Set cnt = Nothing End Sub 

呵呵。 觉得奇怪修改看起来像我自己的代码:)
这将创build标题

 Dim i As Long With rst For i = 1 To .Fields.Count wsSheet.Cells(1, i) = .Fields(i - 1).Name Next i End With 

这将粘贴从A2开始的范围

 rnStart.CopyFromRecordset rst 

rnStart应设置为A2作为logging集开始粘贴的第一个单元格。

 Option Explicit Sub Add_Results_Of_ADO_Recordset() 'This was set up using Microsoft ActiveX Data Components version 2.8 Dim cnt As ADODB.Connection Dim rst As ADODB.Recordset Dim stSQL As String Dim wbBook As Workbook Dim wsSheet As Worksheet Dim rnStart As Range Const stADO As String = "PROVIDER=SQLOLEDB.1;SERVER=192.168.0.300;UID=sa;PWD=sa;DATABASE=sa" 'where BI is SQL Database & AURDWDEV01 is SQL Server Set wbBook = ActiveWorkbook Set wsSheet = wbBook.Worksheets(1) With wsSheet Set rnStart = .Range("A2") End With stSQL = "SELECT sModel,sKodu,sAciklama FROM tbstok " Set cnt = New ADODB.Connection With cnt .CursorLocation = adUseClient .Open stADO .CommandTimeout = 0 Set rst = .Execute(stSQL) End With ' headers Dim i As Long With rst For i = 1 To .Fields.Count wsSheet.Cells(1, i) = .Fields(i - 1).Name Next i End With ' add recordset starting at A2 rnStart.CopyFromRecordset rst 'Here we add the Recordset to the sheet from A2 rnStart.CopyFromRecordset rst 'Cleaning up. rst.Close cnt.Close Set rst = Nothing Set cnt = Nothing End Sub