Results 1 to 9 of 9

Thread: Export data from Excel to SQL

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #5
    VBAX Mentor anandbohra's Avatar
    Joined
    May 2007
    Location
    Mumbai
    Posts
    313
    Location
    hi all pl solve this simple "for loop"

    Sub testexportsql()
        Dim Cn As ADODB.Connection
        Dim ServerName As String
        Dim DatabaseName As String
        Dim TableName As String
        Dim UserID As String
        Dim Password As String
        Dim rs As ADODB.Recordset
        Dim RowCounter As Long
        Dim NoOfFields As Integer
        Dim StartRow As Long
        Dim EndRow As Long
        Dim ColCounter As Integer
        Set rs = New ADODB.Recordset
        ServerName = "ServerName " ' Enter your server name here
        DatabaseName = "DatabaseName " ' Enter your  database name here
        TableName = "TableName " ' Enter your Table name here
        UserID = "UserID" ' Enter your user ID here
        ' (Leave ID and Password blank if using windows Authentification")
        Password = " Password" ' Enter your password here
        NoOfFields = 20 ' Enter number of fields to update (eg. columns in your worksheet)
        StartRow = 3 ' Enter row in sheet to start reading  records
        EndRow = 6 ' Enter row of last record in sheet
        '  CHANGES
        Dim shtSheetToWork As Worksheet
        Set shtSheetToWork = ActiveWorkbook.Worksheets("SQL")
        Set Cn = New ADODB.Connection
        Cn.Open "Driver={SQL Server};Server=" & ServerName & ";Database=" & DatabaseName & _
        ";Uid=" & UserID & ";Pwd=" & Password & ";"
        rs.Open TableName, Cn, adOpenKeyset, adLockOptimistic
        ' EndRow = shtSheetToWork.Cells(Rows.Count, 1).End(xlUp).Row
        For RowCounter = StartRow To EndRow
            rs.AddNew
            For ColCounter = 1 To NoOfFields
                rs(ColCounter - 1) = shtSheetToWork.Cells(RowCounter, ColCounter)
                ColCounter = ColCounter + 1
            Next ColCounter
        Next RowCounter
        rs.UpdateBatch
        ' Tidy up
        rs.Close
        Set rs = Nothing
        Cn.Close
        Set Cn = Nothing
    End Sub
    if u run this code u will get error on this line


     rs(ColCounter - 1) = shtSheetToWork.Cells(RowCounter, ColCounter)
    pl solve this as this code transfer EXCEL data into SQL
    Last edited by Aussiebear; 03-03-2025 at 02:54 AM.

Posting Permissions

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