如何使用vba导出excel中的消息框显示数据以访问数据库表

时间:2017-11-29 07:58:48

标签: excel vba excel-vba vbscript

我在vba中有一个代码,通过该代码,每当我将在特定单元格中保存任何新值时,它将在消息框中显示存储在单元格中的旧值是什么以及我刚保存的新值是什么下面是那个

的代码
Option Explicit

Dim OldVals As New Dictionary

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim myCell As Range

    For Each myCell In Target
        If OldVals.Exists(myCell.Address) Then
           MsgBox "New value of " & Replace(myCell.Address, "$", "") & " is " & myCell.Value & "; old value was " & OldVals(myCell.Address)
        Else
           MsgBox "No old value for " + Replace(myCell.Address, "$", "")
        End If
        OldVals(myCell.Address) = myCell.Value
    Next myCell

End Sub

代码的输出窗口如下图所示 - enter image description here

所以我想一个接一个地使用vba将消息框中显示的值导出到访问数据库表

但是我编写了一个代码来导出并将excel表单元格的值保存到访问数据库表中,代码在下面

Const TARGET_DB = "\Database3.accdb"
    Sub PushTableToAccess()
    Dim cnn As ADODB.Connection
    Dim MyConn
    Dim rst As ADODB.Recordset
    Dim i As Long, j As Long
    Dim Rw As Long

    Sheets("Sheet1").Activate
    Rw = Range("A1").End(xlDown).Row

    Set cnn = New ADODB.Connection
    MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB

    With cnn
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .Open MyConn
    End With



    Set rst = New ADODB.Recordset
    rst.CursorLocation = adUseServer
    rst.Open Source:="Table1", ActiveConnection:=cnn, _
    CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
    Options:=adCmdTable

    For i = 2 To Rw
        rst.AddNew
        For j = 1 To 3
            rst(j) = Cells(i, j).Value
        Next j
        rst.Update
    Next i


    rst.Close
    cnn.Close
    Set rst = Nothing
    Set cnn = Nothing

    End Sub

上面的代码将导出并保存excel单元格中的所有值以访问数据库表。

但是我不知道如何将两个代码组合在一起以便我的第一个代码只要它显示单元格的旧值和新值,当我单击“确定”按钮时它将导出并保存消息框中显示的值(例如 - A1的新值为7;旧值为88)一个接一个地访问数据库表。

0 个答案:

没有答案