【发布时间】:2019-11-25 16:44:03
【问题描述】:
我想自动化这个过程以减少出错的风险。
这是我使用 VBA 的第一天,所以我的技能有些欠缺。我正在尝试自动化我的工作中的一些步骤,因此我需要从 Access 复制 1 列并将其粘贴到 Excel 工作表中。在突变之后,我必须将结果复制/粘贴回 Access(同一表中的另一列)。我一直在寻找有效的 VBA 代码并对其进行测试,但直到现在我还没有找到任何代码。
enter code here
常量 TARGET_DB = "test.accdb"
Sub Test()
Dim cnn As ADODB.Connection
Dim MyConn
Dim rst As ADODB.Recordset
Dim i As Long, j As Long
Dim Rw As Long
Sheets("Informatie").Select
Rw = Range("A2", Range("A2").End(xlDown)).Select
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
'Load all records from Excel to Access.
For i = 2 To Rw
rst.AddNew
For j = 1 To 7
rst(Cells(1, j).Value) = Cells(i, j).Value
Next j
rst.Update
Next i
'Close the connection
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
MsgBox "Alan's work is finished for today"
我希望在 Access 文件中看到一些变化。任何突变都会 是一个开始。但是除了我在 Excel 工作表中选择了正确的范围之外,什么都没有发生。
【问题讨论】: