批量插入数据?

时间:2011-05-02 05:40:55

标签: ms-access vba

我需要一个用户的代码(在数据表中粘贴数据后),当他点击一个按钮时,数据将被插入一个表中(我想在这里使用SQL语句)。除此之外,必须使用DCount函数计算该表中的一个字段。所以我需要计算每条记录。如果想法不清楚,请告诉我,我需要进一步解释。此外,如果有更好的想法,请告诉我们。谢谢!

1 个答案:

答案 0 :(得分:0)

为什么不创建一些VBA来从电子表格中提取数据,将其插入表格然后再次关闭excel。全部按下按钮

请看下面的示例

Dim objApp As Excel.Application
Dim objBook As Excel.Workbook
Dim objSheet As Excel.Worksheet
Dim sSQL As String
Dim Path As String

Set db = CurrentDb()

 Set objBook = Workbooks.Add(Template:=SheetLocation)   'Your excel spreadsheet file goes here where "SheetLocation is typed
            Set objApp = objBook.Parent
                Set objSheet = objBook.Worksheets("Sheet1") 'Name of sheet you want to View
                   objBook.Windows(1).Visible = True
                   objApp.Visible = True

            objApp.DisplayAlerts = False




    Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
' connect to the Access database
Set cn = CurrentProject.Connection

' open a recordset
Set rs = New ADODB.Recordset
rs.Open "INSERT YOUR TABLE NAME HERE", cn, adOpenKeyset, adLockOptimistic, adCmdTable
' all records in a table
r = 2 ' the start row in the worksheet
Do While Len(Range("A" & r).Formula) > 0
' repeat until first empty cell in column A
    With rs
        .AddNew ' create a new record
        ' add values to each field in the record
        .Fields("INSERT THE TABLE FIELD TO DUMP DATA IN HERE") = Range("A" & r).Value
        .Fields("REPEAT AS ABOVE") = Range("B" & r).Value
        .Fields("REPEAT AS ABOVE") = Range("C" & r).Value
        .Fields("REPEAT AS ABOVE") = Range("D" & r).Value
        .Fields("REPEAT AS ABOVE") = Range("E" & r).Value
        .Fields("REPEAT AS ABOVE") = Range("F" & r).Value
        .Fields("REPEAT AS ABOVE") = Range("G" & r).Value
        .Fields("REPEAT AS ABOVE") = Range("H" & r).Value
        ' add more fields if necessary...
        .Update ' stores the new record
    End With
    r = r + 1 ' next row
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
    objApp.Quit