【问题标题】:Retrieving Last Inserted Max Record From MS access to Excel Using ADO使用 ADO 从 MS 访问 Excel 中检索最后插入的最大记录
【发布时间】:2020-09-01 18:49:33
【问题描述】:

您好可能想知道为什么 Copyfromrecordset 不起作用 使用 ADO 有什么解决方法吗?

我只有一个表一号列,它不接受重复。 还需要检索 ID 号才能被其他代码用于多用户目的。

Sub PostData()
Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rst As ADODB.Recordset 'dim the ADO recordset classe here
Dim dbPath
Dim x As Long, i As Long

'add error handling
On Error GoTo errHandler:

dbPath = Sheets("Sheet3").Range("h1").Value

Set cnn = New ADODB.Connection

cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath

Set rst = New ADODB.Recordset 'assign memory to the recordset
Sql = "INSERT INTO DvID(DVnumber)SELECT Max(DVNumber)+1 FROM DvID "
rst.Open Sql, cnn
Sheet3.Range("A2").CopyFromRecordset rst
rst.Close
cnn.Close

Set rst = Nothing
Set cnn = Nothing

On Error GoTo 0
Exit Sub
errHandler:

Set rst = Nothing
Set cnn = Nothing

MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Export_Data"
End Sub

【问题讨论】:

    标签: sql excel vba ado ms-access-2016


    【解决方案1】:

    Remarks看到这一段

    使用 Open 方法的 Source 参数来执行不返回记录的操作查询不是一个好主意,因为没有简单的方法来确定调用是否成功。此类查询返回的 Recordset 将被关闭。要执行不返回记录的查询(例如 SQL INSERT 语句),请改为调用 Command 对象的 Execute 方法或 Connection 对象的 Execute 方法。

    如果您使用单独的选择和插入查询,风险是另一个用户可能会在两者之间创建记录。首选使用自动增量键。有了这个警告尝试

    Sub PostData()
    
        Dim cnn As ADODB.Connection 'dim the ADO collection class
        Dim rst As ADODB.Recordset 'dim the ADO recordset classe here
        Dim dbPath As String, sql As String
        Dim newID As Long
    
        'add error handling
        On Error GoTo errHandler:
    
        dbPath = Sheets("Sheet3").Range("h1").Value
    
        Set cnn = New ADODB.Connection
    
        cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
        Set rst = New ADODB.Recordset 'assign memory to the recordset
    
        rst.Open "SELECT MAX(DVNumber)+1 FROM DvID", cnn
        newID = rst(0)
        cnn.Execute "INSERT INTO DvID(DVnumber) VALUES (" & newID & ")"
    
        Sheet3.Range("A2") = newID
    
        rst.Close
        cnn.Close
        Set rst = Nothing
        Set cnn = Nothing
    
        MsgBox newID & " Inserted", vbInformation
    
        On Error GoTo 0
        Exit Sub
    errHandler:
    
        Set rst = Nothing
        Set cnn = Nothing
    
        MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure PostData"
    
    End Sub
    
    

    【讨论】:

    • 非常感谢。解释得很好
    猜你喜欢
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多