【问题标题】:1004: application defined or object defined error (2nd Loop)1004:应用程序定义或对象定义错误(第二个循环)
【发布时间】:2015-08-18 13:31:33
【问题描述】:

我正在编写一些 vb 来将数据从访问 excel 中导出。传递给 Excel 后,我使用代码格式化工作簿中的一个电子表格,然后保存并关闭文件。它应该多次循环此代码。当我执行代码时,它会创建电子表格的第一次迭代,但在第二次传递时它返回 1004:应用程序定义或对象定义错误。一直在寻找解决方案,但找不到。请帮忙?

================================================

代码如下

On Error GoTo errorhandler

Dim strtable As String
Dim strworksheetpath As String
Dim pickersct As Integer
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlSh As Excel.Worksheet

pickersct = 1
Me.Text7 = 1

Do Until pickersct > Me.Text1

    Me.Text7.Requery
    strworksheetpath = "D:\My Documents\Deliverable" & pickersct & ".xls"
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qry_pickers_Picks_Export", strworksheetpath

    Set xlApp = New Excel.Application
    Set xlWB = xlApp.Workbooks.Open("D:\My Documents\deliverable" & pickersct & ".xls")
    Set xlSh = xlWB.Sheets("qry_pickers_Picks_Export")

        Sheets("qry_pickers_Picks_Export").Activate 'Error occurs after this line
        Sheets("qry_pickers_Picks_Export").Range("H2").Select
        ActiveCell.FormulaR1C1 = "=IF(RC[-3]=1,-1,0)"
        Sheets("qry_pickers_Picks_Export").Range("I2").Select
        ActiveCell.FormulaR1C1 = "=IF(RC[-2]=1,-1,0)"
        Sheets("qry_pickers_Picks_Export").Range("J2").Select
        ActiveCell.FormulaR1C1 = "=RC[-2]+RC[-1]"
        Sheets("qry_pickers_Picks_Export").Range("J2").Select
        Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlNotEqual, _
            Formula1:="=1"

    xlWB.Save
    xlWB.Close
    xlApp.Quit
    Set xlApp = Nothing

    pickersct = pickersct + 1
    Me.Text7 = Me.Text7 + 1
Loop

errorHandlerExit:
  Exit Sub

errorhandler:
  MsgBox "Error No: " & Err.Number & "; Description: " & Err.Description
  Resume errorHandlerExit

【问题讨论】:

  • 在哪一行出现此错误?
  • 建议不要使用 .select 而是使用其他方法。您可以使用以下代码在 1 中执行 2 个步骤:xlSh.Range("H2").FormulaR1C1 = "=IF(RC[-3]=1,-1,0)" 加上您定义 xlSh 但然后不要使用它,就像在我的评论中的代码中我包含了这个一样。

标签: vba excel ms-access


【解决方案1】:

从 Excel 录制的 VBA 通常不能直接在 Access 中使用。我很惊讶它在第一次迭代中运行。

SheetsActiveCell 在不引用 Excel 应用程序对象的情况下无法工作。最好分配对象并始终使用它们。

  • Sheets("qry_pickers_Picks_Export") 替换为xlSh
  • 不要使用.SelectActiveCell.
  • 指定范围,并设置其属性,例如
    xlSh.Range("H2").FormulaR1C1 = "=IF(RC[-3]=1,-1,0)"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多