[如何通过首先查询MAx列并加1来将excel数据导出到MS Access?

问题描述 投票:1回答:1

您好,我制作了一个Excel表单,可在其中访问我的数据库。

首先我先在Excel中编码数据,然后使用命令按钮发布这些数据。

命令按钮中的代码。首先从Access获取最大编号,然后使用该编号完成Excel中要导出到Access的数据。问题是,如果我使用2个及以上的用户同时发布,它将把所有数据合并为一个具有相同编号的数据。我想要的是锁定开放数据,直到发布为止,因为我需要获取一列的最大数量,然后首先添加1,然后导入一整套数据,包括MAX编号作为控制编号。

我尝试使用do While adStateOpen <> 1,也使用IsRecordBusy = True,然后等待并循环,将记录集设置为空,而不是将其关闭两次。但是它将无法使用相同的控制编号来合并数据。

下面是我的代码

Option Explicit

Sub ImportJEData()

Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rst As ADODB.Recordset 'dim the ADO recordset class
Dim dbPath
Dim x As Long, i As Long
Dim nextrow As Long
Dim Var
Dim LockType
Dim SQL
Dim IsRecordBusy


'add error handling
On Error GoTo errHandler:

'Variables for file path and last row of data
dbPath = Sheets("Update Version").Range("b1").Value
Set Var = Sheets("JE FORM").Range("F14")
nextrow = Sheets("LEDGERTEMPFORM").Cells(Rows.Count - 5, 1).End(xlUp).Row

'Initialise the collection class variable
Set cnn = New ADODB.Connection

'Create the ADODB recordset object. for Max Number
Set rst = New ADODB.Recordset 'assign memory to the recordset
LockType = adLockPessimistic

'Do While adStateOpen <> 1
Do While IsRecordBusy = True
Application.Wait (Now + TimeValue("0:00:01") / 1000)
Loop

SQL = "SELECT distinct Max(DVNumber),Max(ChckID) FROM DV "

rst.Open SQL, cnn

Sheets("Max").Range("A2").CopyFromRecordset rst

Set rst = Nothing

Set rst = New ADODB.Recordset 'assign memory to the recordset

rst.Open Source:="DV", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockPessimistic, _
Options:=adCmdTable

On Error Resume Next

'you now have the recordset object
'add the values to it
For x = 7 To nextrow
rst.AddNew
For i = 1 To 37
rst(Sheets("LEDGERTEMPFORM").Cells(6, i).Value) = Sheets("LEDGERTEMPFORM").Cells(x, i).Value
Next i
rst.Update
Next x

'close the recordset
rst.Close
' Close the connection
cnn.Close
'clear memory
Set rst = Nothing
Set cnn = Nothing


'Update the sheet



Application.ScreenUpdating = True

'Clear the data
On Error GoTo 0
Exit Sub
errHandler:

'clear memory
Set rst = Nothing
Set cnn = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Export_Data"

End Sub
excel vba ms-access ado
1个回答
0
投票

我终于用这段代码完成了。我刚刚在访问中添加了另一个表,该表是唯一的,使用sql获取max + 1并将其插入并循环返回(如果由于重复而发生错误)。这是下面的代码

Do
On Error Resume Next 'reset Err.obj.

     'Get the Max ID +1
    Set rst = Nothing
    Set rst = New ADODB.Recordset 'assign memory to the recordset
    SQL = "SELECT Max(ApNumber)+1 FROM PayVoucherID "
    rst.Open SQL, cnn

    'Check if the recordset is empty.
    'Copy Recordset to the Temporary Cell
    Sheets("MAX").Range("A2").CopyFromRecordset rst

    'Insert the Data to Database And Check If no Errors
    Sql2 = "INSERT INTO PayVoucherID(ApNumber)Values('" & Sheets("MAX").Range("A2") & "') "
    cnn.Execute Sql2

Loop Until (Err.Number = 0)

希望这对Excel Front用户有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.