【发布时间】:2013-03-20 12:05:03
【问题描述】:
我一直在尝试到处寻找答案,但我在 VBA 方面的基础技能确实无法帮助我弄清楚我要编写什么代码。
到目前为止我有这个代码:
Sub ADOFromExcelToAccess()
' exports data from the active worksheet to a table in an Access database
' this procedure must be edited before use
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=\\GSS_Model_2.4.accdb;"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "Forecast_T", cn, adOpenKeyset, adLockOptimistic, adCmdTable
' all records in a table
For i = 4 To 16
x = 0
Do While Len(Range("E" & i).Offset(0, x).Formula) > 0
' repeat until first empty cell in column A
With rs
.AddNew ' create a new record
.Fields("Products") = Range("C" & i).Value
.Fields("Mapping") = Range("A1").Value
.Fields("Region") = Range("B2").Value
.Fields("ARPU") = Range("D" & i).Value
.Fields("Quarter_F") = Range("E3").Offset(0, x).Value
.Fields("Year_F") = Range("E2").Offset(0, x).Value
.Fields("Units_F") = Range("E" & i).Offset(0, x).Value
.Update
' stores the new record
End With
x = x + 1
Loop
Next i
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
到目前为止,这段代码完全符合我的要求。我知道要添加一个将根据 4 条规则检查记录是否存在的部分:产品、区域、Quarter_F 和 Year_F 如果它匹配这些,它应该更新另一个字段(Units_F,ARPU)。如果没有,它应该正确运行代码并创建一个新记录。
非常感谢您的帮助,我被困在这里,不知道如何出去。
谢谢
【问题讨论】: