Monday 8 April 2013

How to Import Data from Excel to sql server

'First of all create a table in Sql server. 
'where you keep imported data
 then go to excel which you want to import then developer tab / insert / module/.
in the developer tab / tools / references /select Microsoft Active library 2.7 /
then write you code.
here


Sub Rectangle1_Click()
'TRUSTED CONNECTION
    On Error GoTo errH
  
    Dim con As New ADODB.Connection         'declare variable data type
    Dim rs As New ADODB.Recordset
    Dim strPath As String
    Dim intImportRow As Integer
    Dim name, proj_name, pdf_source, pub, issue, Article, status As String
    Dim year, page  As Integer
    Dim rec_date As String
    Dim server, username, password, table, database As String
   
   With Sheets("Salt Lake and Metiabruz_ZONING")
  
   server = ".\SQLEXPRESS"       'server name
   table = "MstProject"              'my table in sqlserver
   database = "Aptara"              'my database name
  
    If con.State <> 1 Then
  
    con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"   '(this is connection string)
                'con.Open
         
    End If
            'this is the TRUSTED connection string              ' zari
    Set rs.ActiveConnection = con
    intImportRow = 3  ' indciate row number, that means it will start selecting from the very first row
    Do Until .Cells(intImportRow, 1) = ""        'condition untill the row find blank
    name = .Cells(intImportRow, 1)                 'assign the value
    proj_name = .Cells(intImportRow, 2)
    pdf_source = .Cells(intImportRow, 3)
    year = .Cells(intImportRow, 4)
    rec_date = .Cells(intImportRow, 5)
    pub = .Cells(intImportRow, 6)
    issue = .Cells(intImportRow, 7)
    Article = .Cells(intImportRow, 8)
    page = .Cells(intImportRow, 9)
    status = .Cells(intImportRow, 13)
    con.Execute "insert into MstProject (Operataor_Name,Proj_Name,Pdf_Source,Yr,Rec_Date,Pub,Issue,Article_No,Page,Status) values ('" & name & "', '" & proj_name & "', '" & pdf_source & "','" & year & "','" & rec_date & "','" & pub & "','" & issue & "','" & Article & "','" & page & "','" & status & "')"     
    intImportRow = intImportRow + 1         ' increase the row
    Loop
    MsgBox "Done importing", vbInformation
          
    con.Close
    Set con = Nothing
  
    End With
    Exit Sub

errH:
    MsgBox Err.Description
End Sub





Followers