以下是我的代码,它运行正常,但我遇到了一个小问题。
我有两张不同的纸张:在第一张纸上,有一个按钮来获取数据。这是有效的,我可以在第二张表中看到数据。但问题是得到表头。我的代码无法检索标题。
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
答案 0 :(得分:2)
和合。修改看起来几乎像我自己的代码感觉很奇怪:) 这会创建标题
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作为记录集开始粘贴的第一个单元格。
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