Save Excel 2003 worksheet into an Access 2003 table

て烟熏妆下的殇ゞ 提交于 2019-12-25 03:36:23

问题


I'm trying to write a macro to export a single row from a single worksheet from an Excel 2003 workbook to a new row in an Access 2003 table. I'm new to VBA, and everything I've found on the web refers to going the other way -- from Access to Excel. I want this to be an export, not a link, and I don't care about keeping them synced after the export.


回答1:


This sample code assumes a few things:

  1. You are inserting two values, which are found in A2 and B2.
  2. The values are both strings
  3. You have a table called TestTable, containing two columns

    Public Sub ExportRecord()
    
    
    
    On Error GoTo ErrRoutine
    
    
    Dim conn As New ADODB.Connection
    Dim rs As ADODB.Recordset
    
    
    conn.Open "Your_DSN_Goes_Here", "userId", "pwd"
    
    
    Set rs = New ADODB.Recordset
    rs.Open "TestTable", conn, adOpenDynamic, adLockOptimistic, adCmdTable
    
    
    rs.AddNew
    
    
    rs.Fields("Col1") = CStr(Sheet1.Cells(2, 1))
    rs.Fields("Col2") = CStr(Sheet1.Cells(2, 2))
    
    
    rs.Update
    
    
    Set rs = Nothing
    Set conn = Nothing
    
    
    Exit Sub
    
    ErrRoutine:
    MsgBox Err.Description
    
    End Sub


来源:https://stackoverflow.com/questions/3806770/save-excel-2003-worksheet-into-an-access-2003-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!