0
'Create the recordset
Set dbRecordset = New ADODB.Recordset
dbRecordset.CursorLocation = adUseServer
dbRecordset.Open Source:="Table1", _
ActiveConnection:=dbConnection, _
CursorType:=adOpenDynamic, _
LockType:=adLockOptimistic, _
Options:=adCmdTable

'dbRecordset.AddNew


dbRecordset(Cells(2, 3).Value) = Cells(1, 1).Value

dbRecordset.Update

'Close the connections.
dbRecordset.Close
dbConnection.Close

我正在尝试制作一个具有将数据存储到 excel 访问权限的功能的应用程序(从未使用过访问权限)。我能够连接它们,并将值发送到数据库。我相信我遇到的问题是上面的代码。dbRecordset(Cells(2, 3) 对我来说似乎值应该转到行/记录 2 字段 3,但它写入 (2,3)。尝试写入 (1,1) 会给我一个错误。我想我可以为每个循环编写一个移动我需要的数据的循环,但我不明白它会去哪里。

可以绕过所有这一切的事情是,如果我可以触发一个 DoCmd.TransferSpreadsheet 方法,该方法已经从 excel 内置。我不知道写类似(sql,shell?)的语法。如果你能指出我在哪里写一个 doCmd 命令的正确方向,那将不胜感激,因为它比循环快得多。

4

1 回答 1

0

稍微调整一下。您可以从 Excel 运行它:

Sub LoadSheet()
Dim accappl As Access.Application
Dim strpathdb As String
Dim strpathxls As String
Dim myrange As String, myrow1 As String, myrow2 As String

myrow1 = Range("a1").End(xlDown).End(xlDown).Row
myrow2 = Range("a1").End(xlDown).End(xlDown).End(xlDown).Row

myrange = ActiveSheet.Name & "!A" & myrow1 & ":H" & myrow2

'path to the database
strpathdb = "X:\cre\dep\STRAT_PLAN\StratPlan.mdb"
'path to the upload file
strpathxls = ActiveWorkbook.FullName
Set accappl = New Access.Application

accappl.OpenCurrentDatabase strpathdb

accappl.DoCmd.TransferSpreadsheet transfertype:=acImport, _
            tablename:="Tbl_Growth_Metric", _
            Filename:=strpathxls, Hasfieldnames:=True, _
            Range:=myrange, SpreadsheetType:=5
            'The Spreadsheet type = 5 specifies an Excel 5.0/7.0 file
            'format

MsgBox "All records are loaded"

accappl.Quit

End Sub
于 2013-06-17T19:50:41.797 回答