我是新的excel VBA。我有一個要求,我必須將表值從SQL Server 2005複製到Excel工作表。我已經在Google上搜索並編寫了一個代碼(以下列出)。如何使用CopyFromRecordset執行'插入行'而不是'複製行'(excel vba)
在這個excel表格中有一組固定的顯示圖例和日期的行。這些行應在數據庫/表值打印後顯示。正如我使用.CopyFromRecordset將記錄集中的記錄複製到Excel表一樣,顯示圖例和日期的行將被數據庫/表值覆蓋。請讓我知道如何執行插入行而不是複製。或者有什麼辦法來達到上述目的。
--- CODE ------------
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
在運行'.CopyFromRecordset方法'之前,你需要檢查你的'rs變量'的行數。然後插入適當數量的行,然後運行該方法... –