+ Reply to Thread
Results 1 to 2 of 2

How to perform 'insert rows' instead of 'copy rows' using .copyrecordset (excel vba)

  1. #1
    Registered User
    Join Date
    07-11-2013
    Location
    Bangalore, India
    MS-Off Ver
    Excel 2007
    Posts
    1

    How to perform 'insert rows' instead of 'copy rows' using .copyrecordset (excel vba)

    I am new to excel VBA. I have a requirement where I have to copy table values from sql server 2005 to an excel worksheet. I have googled and written a code for the above requirement (listed below).

    In this excel sheet there are fixed set of rows which displays legends and dates. These rows should be displayed after the database/table values are printed. As I am using .CopyFromRecordset to copy the records from the recordset to excel sheet, the rows which are displaying legend and dates are overwritten with the database/table values. Please let me know how to perform insert of rows instead of copy. Or is there any way to achieve the above.

    ---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

  2. #2
    Forum Guru JosephP's Avatar
    Join Date
    03-27-2012
    Location
    Ut
    MS-Off Ver
    2003/10
    Posts
    7,328

    Re: How to perform 'insert rows' instead of 'copy rows' using .copyrecordset (excel vba)

    cross-posted: http://stackoverflow.com/questions/1...mrecordsetexce
    Josie

    if at first you don't succeed try doing it the way your wife told you to

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1