我正在写一些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
答案 0 :(得分:0)
从Excel中记录的VBA通常不能直接在Access中使用。我很惊讶它在第一次迭代中运行。
如果不引用Excel应用程序对象, Sheets
或ActiveCell
将无效。最好分配对象并始终使用它们。
Sheets("qry_pickers_Picks_Export")
替换为xlSh
。 .Select
和ActiveCell.
xlSh.Range("H2").FormulaR1C1 = "=IF(RC[-3]=1,-1,0)"