我是擅长 VBA 的新手。我有一个要求,我必须将表值从 sql server 2005 复制到 Excel 工作表。我已经用谷歌搜索并为上述要求编写了代码(如下所列)。
在此 Excel 表中,有一组固定的行显示图例和日期。这些行应在打印数据库/表值后显示。当我使用 .CopyFromRecordset 将记录从记录集中复制到 Excel 工作表时,显示图例和日期的行将被数据库/表值覆盖。请让我知道如何执行插入行而不是复制。或者有什么办法可以达到上述目的。
- -代码 - - - - - -
Sub GETSQLSERVERDATA()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim USERID As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
USERID = Range("C1").Value 'Input form excel template.
Server_Name = "" 'Enter server name
Database_Name = "" 'Enter database name
User_ID = "" 'SQL server user id
Password = "" SQL server password
SQLStr = "SELECT END_DATE,PERIOD FROM PERIOD_MAP WHERE USERID='" + USERID + "'"
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
With Worksheets("Sheet1").Range("A2:D2") ' Enter your sheet name and range here
.ClearContents
.CopyFromRecordset rs
End With
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub