Insert Data from Excel into Access

前端 未结 5 1240
不思量自难忘°
不思量自难忘° 2020-12-18 11:04

I\'ve made some code to insert data from an excel table in to an access database - my code is as follow:

    Sub AddData()

Dim Cn As ADODB.Connection

Set C         


        
5条回答
  •  醉梦人生
    2020-12-18 12:01

    The SELECT statement runs on the database itself, but you want to send values from EXCEL. So you must use

    cn.Execute "INSERT .... VALUES (" & excelcell_or_variable & ");"
    

    eventually in a loop to proces all rows/columns etc.

    Hope that helps

    good luck

    EDIT ... don't forget quotation marks surrounding CHAR's and interpunctations; I use

    ' ....
    ' .... "...VALUES (" & T(Q(MyStringCell)) & T(MyNumCell) & Q(MyLastTextCell) & ");"
    ' ....
    
    ' surrounds a string by single quotes
    Private Function Q(Arg as String) As String
        Q = "'" & Arg & "'"
    Return
    
    ' appens a comma to a string
    Private Function T(Arg as String) As String
        T = Arg & ","
    Return
    

    EDIT 2 I asume that in EXCEL the values you want to insert into the DB are all in 1 row ...

    Suppose you have a source_range which contains more than 1 row, you must fire the INSERT statement for each row in that range. You use the .Rows property to return a single row from a range. And you send multiple columns to the INSERT statement within the same row by using .Cells(1, 1), .Cells(1,2) .... and so on

    example:

    Sub Test()
    Dim MyRange As Range, MyRow As Range
    
        Set MyRange = Range([B4], [C8])   ' source range
    
        For Each MyRow In MyRange.Rows    ' get one row at the time from source range 
            Debug.Print MyRow.Cells(1, 1), MyRow.Cells(1, 2)
            ' replace the above by your INSERT statement
        Next MyRow
    
    End Sub
    

提交回复
热议问题