从新工作表执行ADO宏时遇到问题

时间:2018-10-16 11:02:38

标签: excel vba

我试图用一个按钮从新工作表中执行宏,以便它在另一个工作表中运行(名为“ ARF导出”)。

不幸的是,我不知道如何设置要在其中运行宏的工作表(“ ARF导出”)。请您告诉我如何进行吗?

在其他工作表中运行此代码时遇到的错误是:

错误3265项无法在过程export_data中与请求的名称或顺序相对应的集合中找到

当我进入Debug时,直到最后我都没有收到错误,但是它跳过了我接下来的第38行上的For循环

for x = 2 To nextrow
        DatabaseData.AddNew
        For i = 1 To 35
            DatabaseData(Cells(1, i).Value) = Worksheets("ARF Export").Cells(x, i).Value
            Next i
        DatabaseData.Update
    Next x

下面的所有代码---

Option Explicit

Sub CopyDatatoAccess()
    Dim DatabaseConn As ADODB.Connection
    Dim DatabaseData As ADODB.Recordset
    Dim Pathway
    Dim x As Long, i As Long
    Dim nextrow As Long


    On Error GoTo errorhandler:

    Pathway = Worksheets("ARF Export").Range("AR2").Value
    nextrow = Worksheets("ARF Export").Range("As2").Value


    Set DatabaseConn = New ADODB.Connection

    If Worksheets("ARF Export").Range("A2").Value = "" Then
    MsgBox "ARF form is not present for Upload"
    Exit Sub
    End If

    DatabaseConn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Pathway

    Set DatabaseData = New ADODB.Recordset

DatabaseData.Open Source:="ARFs", _
    ActiveConnection:=DatabaseConn, _
    CursorType:=adOpenDynamic, _
    LockType:=adLockOptimistic, _
    Options:=adCmdTable

For x = 2 To nextrow
    DatabaseData.AddNew
    For i = 1 To 35
        DatabaseData(Cells(1, i).Value) = Worksheets("ARF Export").Cells(x, i).Value
        Next i
        DatabaseData.Update
    Next x

    DatabaseData.Close
    DatabaseConn.Close

    Set DatabaseData = Nothing
    Set DatabaseConn = Nothing

MsgBox "The ARF is now uploaded"
Application.ScreenUpdating = True

Worksheets("ARF Export").Cells.Range("AK2").Value = Worksheets("ARF Export").Cells.Range("AK4").Value

Worksheets("ARF Export").Cells.Range("AK5").Value = Worksheets("ARF Export").Cells.Range("AK4").Value + 1

   On Error GoTo 0
   Exit Sub
errorhandler:

    Set DatabaseData = Nothing
    Set DatabaseConn = Nothing
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Export_Data"
    End Sub

1 个答案:

答案 0 :(得分:0)

感谢您的帮助

-事实证明,一旦执行此操作,我需要引用DatabaseData(Cells(1, i).Value)

For x = 2 To nextrow
    DatabaseData.AddNew
    For i = 1 To 35
        DatabaseData(Worksheets("ARF Export").Cells(1, i).Value) = Worksheets("ARF Export").Cells(x, i).Value
        Next i
        DatabaseData.Update
    Next x

效果很好。谢谢大家的帮助!